<?php


/**
 * 订单操作类 billHandler
 * @package  htdocs
 * @subpackage  module/base
 * @version 1.0  
 */

class billHandler {

    private $dbca;

    private $eai;

    public function __construct( &$dbca, &$eai = null ) {
        $this->dbca = $dbca;
        if (!is_null($eai))
            $this->eai = $eai;
    }

    /**
     * 新增订单信息
     * @param array $bill_array 订单数组
     * @param null|string $operator 操作人
     * @return array
     * @throws Exception
     */
    public function saveBill( &$bill_array, $operator=null ) {

        //订单操作记录数组
        $bill_log_array = array(
            'goods' => array(),
            'other' => array(),
            'operator' => ''
        );

        //临时数组
        $temp_array = array(
            'goods_store' => array(), //用于检查库存
            'goods_promotion' => array(), //查询订单促销
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array()
        );

        if (!isset($bill_array['use_coupon']['amount'])) {
            $bill_array['use_coupon']['amount'] = 0;
        }

        $bill_array['master']['bill_totalMoney'] = 0; //商品总金额
        $bill_array['master']['bill_totalPaid'] = 0; //商品实售总金额
        $bill_array['master']['bill_totalPoints'] = 0; //商品总赠送积分
        $bill_array['master']['bill_pointsPrice'] = 0; //商品总积分价格
        $bill_array['master']['bill_subtract_money'] = 0; //订单立减金额
        $bill_array['master']['bill_coupon_money'] = $bill_array['use_coupon']['amount'] ; //订单优惠券抵扣金额
        $bill_array['master']['bill_card_money'] = 0; //订单代金卡抵扣金额
        $bill_array['master']['bill_totalAmount'] = 0; //商品总数量
        $bill_array['master']['total_weight'] = 0; //商品总重量
        $datetime = date(G_DEFAULT_DATETIME_FORMAT); //下单时间

        try {

            //实例化公共类
            $commHandler = new commHandler( $this->dbca );


            //实例化会员类
            $customerHandler = new customerHandler( $this->dbca );


            //实例化商品类
            $goodsHandler = new goodsHandler( $this->dbca );


            //实例化系统类
            $systemHandler = new systemHandler( $this->dbca );


            //实例促销类
            $promotionHandler = new promotionHandler( $this->dbca );


            //查询会员信息
            $c_arg_array = array(
                'pcustID' => $bill_array['pcustID'],
                'useFlg' => 1
            );
            $customer_array = $customerHandler->getCustomerInfo( $c_arg_array );
            if (!$customer_array) {
                throw new Exception('会员信息没有找到', 404);
            }

            //会员名
            $custID =& $customer_array[0]['custID'];

            //如果操作人值为空，默认为会员名
            if (is_null($operator)) {
                $operator = $custID;
            }

            //获得会员等级信息
            $cust_rank = $customerHandler->getCustRand( $bill_array['pcustID'] );

            //订单号
            $bill_no = $commHandler->generate_seqno('seqno_bill');

            $bill_goods_array = $bill_array['goods'];
            $bill_array['goods'] = array();

            //保存订单商品信息（普通商品）
            if (isset($bill_goods_array['general'])) {

                $goods_arg_array = array(
                    'useFlg' => 1,
                    'forSale' => 1
                );

                foreach ($bill_goods_array['general'] as &$general) {

                    //查询并检查商品信息
                    $goods_arg_array['postID'] = $general['postID'];
                    $goods_array = $goodsHandler->searchGoodsSale( $goods_arg_array );
                    if (!$goods_array) {
                        throw new Exception('商品信息没有找到', 404);
                    }

                    //根据会员等级计算商品价格及积分，同时检查商品促销活动
                    $goods_array['goods_amount'] = $general['goods_amount'];
                    $goods_array['addPoints'] = 0;
                    $goods_array['goods_from'] = 1; //默认商品来源为：普通商品
                    $goodsHandler->shopCalculationGoodsPrice( $cust_rank, $goods_array, $promotionHandler );

                    //统计商品信息
                    $bill_array['master']['bill_totalMoney'] += $goods_array['salePrice'] * $goods_array['goods_amount']; //商品总金额
                    $bill_array['master']['bill_totalPaid'] += $goods_array['price'] * $goods_array['goods_amount']; //商品实售总金额
                    $bill_array['master']['bill_totalPoints'] += $goods_array['salePoints'] * $goods_array['goods_amount']; //商品总赠送积分
                    $bill_array['master']['bill_pointsPrice'] += $goods_array['addPoints'] * $goods_array['goods_amount']; //商品总积分价格
                    $bill_array['master']['total_weight'] += $goods_array['goodsWeight'] * $goods_array['goods_amount']; //商品总重量
                    $bill_array['master']['bill_totalAmount'] += $goods_array['goods_amount']; //商品总数量
                    $temp_array['goods'][] = $goods_array['goodsName'];

                    //保存订单普通商品

                    $goods_index = $general['postID'] . '1';

                    $bill_array['goods'][$goods_index] = array(
                        'uuid' => make_uuid(),
                        'timeStamp' => $datetime,
                        'creator' => $operator,
                        'createTime' => $datetime,
                        'bill_no' => $bill_no,
                        'goods_goodsID' => $goods_array['goodsID'],
                        'goods_postID' => $goods_array['postID'],
                        'goods_name' => $goods_array['goodsName'],
                        'goods_spec' => $goods_array['spec'],
                        'goods_amount' => $goods_array['goods_amount'],
                        'goods_storePrice' => $goods_array['salePrice'],
                        'goods_purchasePrice' => $goods_array['price'],
                        'goods_pointsPrice' => $goods_array['addPoints'],
                        'goods_points' => $goods_array['salePoints'],
                        'goods_from' => $goods_array['goods_from'],
                        'goods_groupID' => 0,
                        'goods_status' => 1,
                        'goodsWeight' => $goods_array['goodsWeight'],
                        'product_code' => $goods_array['product_code']
                    );

                    //商品赠品
                    if (!empty($goods_array['promotion'])) {

                        foreach($goods_array['promotion'] as &$p) {

                            if (empty($p['gift']))
                                continue;

                            foreach($p['gift'] as &$g) {

                                $goods_index = $g['postID'] . '3';

                                if (isset($bill_array['goods'][$goods_index])) {

                                    $bill_array['goods'][$g['postID'] . '3']['goods_amount'] += $g['saleAmount'] * $general['goods_amount'];

                                } else {
                                	
                                    $bill_array['goods'][$goods_index] = array(
                                        'uuid' => make_uuid(),
                                        'timeStamp' => $datetime,
                                        'creator' => $operator,
                                        'createTime' => $datetime,
                                        'bill_no' => $bill_no,
                                        'goods_goodsID' => $g['goodsID'],
                                        'goods_postID' => $g['postID'],
                                        'goods_name' => $g['goodsName'],
                                        'goods_spec' => $g['spec'],
                                        'goods_amount' => $g['saleAmount'] * $general['goods_amount'],
                                        'goods_storePrice' => $g['salePrice'],
                                        'goods_purchasePrice' => 0,
                                        'goods_pointsPrice' => 0,
                                        'goods_points' => 0,
                                        'goods_from' => 3,
                                        'goods_groupID' => 0,
                                        'goods_status' => 1
                                    );

                                }

                            }

                        }

                    }

                    //用于检查库存
                    $temp_array['goods_store'][$goods_array['goodsID']] = $goods_array['goods_amount'];

                    //用于检查订单促销
                    $temp_array['goods_promotion'][] = array(
                        'postID' => $goods_array['postID'],
                        'price' => $goods_array['price'],
                        'goodsAmount' => $goods_array['goods_amount'],
                    );

                }

            }

            /**
             * 闪购商品
             */
            if (isset($bill_goods_array['quick'])) {

                $kill_goods_array =& $bill_goods_array['quick'][0];

                $goods_index = $kill_goods_array['postID'] . '6';

                $bill_array['goods'][$goods_index] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'goods_goodsID' => $kill_goods_array['goodsID'],
                    'goods_postID' => $kill_goods_array['postID'],
                    'goods_name' => $kill_goods_array['goodsName'],
                    'goods_spec' => $kill_goods_array['spec'],
                    'goods_amount' => $kill_goods_array['goods_amount'],
                    'goods_storePrice' => $kill_goods_array['salePrice'],
                    'goods_purchasePrice' => $kill_goods_array['price'],
                    'goods_pointsPrice' => 0,
                    'goods_points' => 0,
                    'goods_from' => 6,
                    'goods_groupID' => 0,
                    'goods_status' => 1,
                    'goodsWeight' => $kill_goods_array['goodsWeight'],
                    'product_code' => $kill_goods_array['product_code']
                );

                //统计商品信息
                $bill_array['master']['bill_totalMoney'] += $kill_goods_array['salePrice'] * $kill_goods_array['goods_amount']; //商品总金额
                $bill_array['master']['bill_totalPaid'] += $kill_goods_array['price'] * $kill_goods_array['goods_amount']; //商品实售总金额
                $bill_array['master']['total_weight'] += $kill_goods_array['goodsWeight'] * $kill_goods_array['goods_amount']; //商品总重量
                $bill_array['master']['bill_totalAmount'] += $kill_goods_array['goods_amount']; //商品总数量
                $temp_array['goods'][] = $kill_goods_array['goodsName'];

            }
			
            /**
             * 组合商品
             */
            if ( isset($bill_goods_array['group']) && !empty($bill_goods_array['group']) ) {

                //循环组合信息
                foreach ( $bill_goods_array['group'] as $groupDetail ){

                    //循环组合中的商品
                    foreach( $groupDetail['goods'] as $group_goods ){

                        $goods_index = $group_goods['postID'] . '7' . $groupDetail['detail']['id'];

                        $bill_array['goods'][$goods_index] = array(
                            'uuid' => make_uuid(),
                            'timeStamp' => $datetime,
                            'creator' => $operator,
                            'createTime' => $datetime,
                            'bill_no' => $bill_no,
                            'goods_goodsID' => $group_goods['goodsID'],
                            'goods_postID' => $group_goods['postID'],
                            'goods_name' => $group_goods['goodsName'],
                            'goods_spec' => $group_goods['spec'],
                            'goods_amount' => $group_goods['goods_amount'] * $groupDetail['detail']['group_amount'],
                            'goods_storePrice' => $group_goods['salePrice'],
                            'goods_purchasePrice' => $group_goods['price'],
                            'goods_pointsPrice' => 0,
                            'goods_points' => 0,
                            'goods_from' => 7,
                            'goods_groupID' => $groupDetail['detail']['id'],
                            'goods_status' => 1,
                            'goodsWeight' => $group_goods['goodsWeight'],
                            'product_code' => $group_goods['product_code']
                        );

                        $bill_array['master']['goods_name_str'] .= $group_goods['goodsName'] . '::'; //商品名称字符串
                        $bill_array['master']['total_weight'] += $group_goods['goodsWeight'] * $group_goods['goods_amount']; //商品总重量

                    }

                    //统计商品信息
                    $bill_array['master']['bill_totalAmount'] += $groupDetail['detail']['total_amount'] * $groupDetail['detail']['group_amount'];   //组合数量*组合内商品总数
                    $bill_array['master']['bill_totalMoney']  += $groupDetail['detail']['total_sale'] * $groupDetail['detail']['group_amount'];     //组合数量*组合内商品总销售价格
                    $bill_array['master']['bill_totalPaid']   += $groupDetail['detail']['total_price'] * $groupDetail['detail']['group_amount'];    //组合数量*组合内商品总实售价格

                }

            }
            
            /**
             * 超值选购
             */
            if ( isset($bill_goods_array['choice']) && !empty($bill_goods_array['choice']) ) {

                //循环组合信息
                foreach ( $bill_goods_array['choice'] as $groupDetail ){

                    //循环组合中的商品
                    foreach( $groupDetail['goods'] as $group_goods ){

                        $goods_index = $group_goods['postID'] . '8' . $groupDetail['goodsChoiceID'];

                        $bill_array['goods'][$goods_index] = array(
                            'uuid' => make_uuid(),
                            'timeStamp' => $datetime,
                            'creator' => $operator,
                            'createTime' => $datetime,
                            'bill_no' => $bill_no,
                            'goods_goodsID' => $group_goods['goodsID'],
                            'goods_postID' => $group_goods['postID'],
                            'goods_name' => $group_goods['goodsName'],
                            'goods_spec' => $group_goods['spec'],
                            'goods_amount' => $group_goods['goods_amount'] * $groupDetail['group_amount'],
                            'goods_storePrice' => $group_goods['marketPrice'],
                            'goods_purchasePrice' => $group_goods['salePrice'],
                            'goods_pointsPrice' => 0,
                            'goods_points' => 0,
                            'goods_from' => 8,
                            'goods_groupID' => $groupDetail['goodsChoiceID'],
                            'goods_status' => 1,
                            'goodsWeight' => $group_goods['goodsWeight'],
                            'product_code' => $group_goods['product_code']
                        );

                        $bill_array['master']['goods_name_str'] .= $group_goods['goodsName'] . '::'; //商品名称字符串
                        $bill_array['master']['total_weight'] += $group_goods['goodsWeight'] * $group_goods['goods_amount']; //商品总重量

                    }

                    //统计商品信息
                    $bill_array['master']['bill_totalAmount'] += $groupDetail['goodsCount'] * $groupDetail['group_amount'];   //组合数量*组合内商品总数
                    $bill_array['master']['bill_totalMoney']  += $groupDetail['totalPrice'] * $groupDetail['group_amount'];     //组合数量*组合内商品总销售价格
                    $bill_array['master']['bill_totalPaid']   += $groupDetail['goodsChoicePrice'] * $groupDetail['group_amount'];    //组合数量*组合内商品总实售价格

                }

            }

            /**
             * 积分换购商品
             */
            if (isset($bill_goods_array['points'])) {

                foreach( $bill_goods_array['points'] as &$points ){
                	
                	//检查该商品是否为积分商品
			    	$arg_points_array = array(
			    		'id' => $points['product_code'],
			    		'startDate' => date(G_DEFAULT_DATETIME_FORMAT)
			    	);
			    	
			    	$points_result = $promotionHandler->validPointsMallGoods( $arg_points_array );
			    	
			    	if (isset($points_result[0]) && !empty($points_result[0])) {
			    		$points['addPoints'] = $points_result[0]['points'];
			    		$points['price'] = $points_result[0]['pointsPrice'];
			    	}
			    	//检查该商品是否为积分商品 end
                	

                    $goods_index = $points['postID'] . '9';

                    $bill_array['goods'][$goods_index] = array(
                        'uuid' => make_uuid(),
                        'timeStamp' => $datetime,
                        'creator' => $operator,
                        'createTime' => $datetime,
                        'bill_no' => $bill_no,
                        'goods_goodsID' => $points['goodsID'],
                        'goods_postID' => $points['postID'],
                        'goods_name' => $points['goodsName'],
                        'goods_spec' => $points['spec'],
                        'goods_amount' => $points['goods_amount'],
                        'goods_storePrice' => $points['salePrice'],
                        'goods_purchasePrice' => $points['price'],
                        'goods_pointsPrice' => $points['addPoints'],
                        'goods_points' => 0,
                        'goods_from' => 9,
                        'goods_groupID' => 0,
                        'goods_status' => 1,
                        'goodsWeight' => $points['goodsWeight'],
                        'product_code' => $points['product_code']
                    );

                    //统计商品信息
                    $bill_array['master']['bill_totalMoney'] += $points['salePrice'] * $points['goods_amount']; //商品总金额
                    $bill_array['master']['bill_totalPaid'] += $points['price'] * $points['goods_amount']; //商品实售总金额
                    $bill_array['master']['bill_pointsPrice'] += $points['addPoints'] * $points['goods_amount']; //商品总积分价格
                    $bill_array['master']['total_weight'] += $points['goodsWeight'] * $points['goods_amount']; //商品总重量
                    $bill_array['master']['bill_totalAmount'] += $points['goods_amount']; //商品总数量
                    $temp_array['goods'][] = $points['goodsName'];

                }

            }
             
            if ($bill_array['master']['bill_totalAmount'] == 0)
                throw new Exception('订单商品为空，请选择商品', 406);


            //计算运费
            $bill_array['master']['deliver_fee'] = $systemHandler->checkoutCalculateFreight($bill_array['master']['send_region_id'], $bill_array['master']['total_weight']);
            $bill_array['master']['deliver_feePaid'] =& $bill_array['master']['deliver_fee'];

            /**
             * 订单赠品或换购商品
             */
            if (isset($bill_goods_array['gift'])) {

                foreach ($bill_goods_array['gift'] as &$c_g) {

                    $goods_index = $c_g['postID'] . $c_g['goods_from'];

                    //保存订单普通商品
                    $bill_array['goods'][$goods_index] = array(
                        'uuid' => make_uuid(),
                        'timeStamp' => $datetime,
                        'creator' => $operator,
                        'createTime' => $datetime,
                        'bill_no' => $bill_no,
                        'goods_goodsID' => $c_g['goodsID'],
                        'goods_postID' => $c_g['postID'],
                        'goods_name' => $c_g['goodsName'],
                        'goods_spec' => $c_g['spec'],
                        'goods_amount' => $c_g['goods_amount'],
                        'goods_storePrice' => $c_g['salePrice'],
                        'goods_purchasePrice' => $c_g['price'],
                        'goods_pointsPrice' => $c_g['addPoints'],
                        'goods_points' => $c_g['salePoints'],
                        'goods_from' => $c_g['goods_from'],
                        'goods_groupID' => $c_g['goods_groupID'],
                        'goods_status' => 1
                    );

                    //统计商品信息
                    $bill_array['master']['bill_totalMoney'] += $c_g['salePrice'] * $c_g['goods_amount']; //商品总金额
                    $bill_array['master']['bill_totalPaid'] += $c_g['price'] * $c_g['goods_amount']; //商品实售总金额
                    $bill_array['master']['total_weight'] += $c_g['goodsWeight'] * $c_g['goods_amount']; //商品总重量
                    $bill_array['master']['bill_totalAmount'] += $c_g['goods_amount']; //商品总数量
                    $temp_array['goods'][] = $c_g['goodsName'];

                }

            }


            //=======================================
            //订单商品日志
            //=======================================
            $goods_from_array = array(
                '1' => '普通商品',
                '3' => '赠品',
                '4' => '订单赠品',
                '5' => '订单换购商品',
                '6' => '秒杀商品',
                '7' => '套装商品',
                '8' => '超值选购商品',
                '9' => '积分兑换'
            );
            foreach ($bill_array['goods'] as &$b_goods) {

                $bill_log_array['goods'][] = sprintf('<span class="red">新增%s</span>：%s', $goods_from_array[$b_goods['goods_from']], $b_goods['goods_name']);
                $bill_log_array['goods'][] = '　　规格：' . $b_goods['goods_spec'];
                $bill_log_array['goods'][] = '　　数量：' . $b_goods['goods_amount'];
                $bill_log_array['goods'][] = '　　单价：' . $b_goods['goods_purchasePrice'];
                $bill_log_array['goods'][] = '优惠金额：' . round($b_goods['goods_storePrice'] - $b_goods['goods_purchasePrice'], 2);
                $bill_log_array['goods'][] = '　总金额：' . round($b_goods['goods_amount'] * $b_goods['goods_purchasePrice'], 2);

                $b_goods['bill_goods_no'] = $commHandler->generate_seqno('seqno_bill_goods');

            }


            /**
             * 查询订单促销活动
             */
            if (!empty($temp_array['goods_promotion'])) {

                $bill_promotion_array = $promotionHandler->searchBillPromotion( $temp_array['goods_promotion'] );

                if (isset($bill_promotion_array['meet'])) {

                    foreach($bill_promotion_array['meet'] as &$p) {

                        if ($p['type'] == 1) {
                            $bill_array['master']['bill_subtract_money'] += $p['subtractMoney'] * $p['multiple'];
                        } else if ($p['type'] == 2) {
                            $bill_array['master']['deliver_fee'] = 0;
                        } else if ($p['type'] == 4) {
                            foreach($p['coupon'] as &$coupon) {
                                $bill_array['coupon'][] = array(
                                    'uuid' => make_uuid(),
                                    'timeStamp' => $datetime,
                                    'creator' => $operator,
                                    'createTime' => $datetime,
                                    'bill_no' => $bill_no,
                                    'couponID' => $coupon['couponID'],
                                    'couponName' => $coupon['couponName'],
                                    'couponNum' => $coupon['couponNum'] * $p['multiple'],
                                    'bill_status' => $p['bill_status']
                                );
                            }
                        }
                    }

                }

            }

            //订单总金额（商品实际金额 - 订单立减金额 + 运费）
            $surplus_money = $bill_array['master']['bill_totalPaid'] - $bill_array['master']['bill_subtract_money'] + $bill_array['master']['deliver_fee'] - $bill_array['use_coupon']['amount'];

            //已支付的金额
            $paid = 0;

            //扣除余额
            if (isset($bill_array['balance'])) {

                $payTypeID = &$bill_array['balance']['payTypeID'];
                $payTypeName = &$bill_array['balance']['payTypeName'];
                $pay_amount = &$bill_array['balance']['pay_amount'];

                //检查订单支付余额是否大于订单总金额
                if ($pay_amount + $paid > $surplus_money)
                    throw new Exception('使用的账户余额大于订单应付金额', 406);

                //检查账户余额
                $result_array = $this->eai->memberAccount( $bill_array['pcustID'], 2, $this->dbca );
                if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $surplus_money)
                    throw new Exception('使用的账户余额大于可用账户余额', 406);


                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => $payTypeID,
                    'payTypeName' => $payTypeName,
                    'type' => $bill_array['balance']['type'],
                    'pay_amount' => $pay_amount,
                    'deduct_amount' => $pay_amount
                );

                $temp_array['pay_id'][] = $payTypeID;
                $temp_array['pay_name'][] = $payTypeName;

                $paid += $pay_amount;

            }

            $surplus_money -= $paid;


            //扣除积分
            if ($bill_array['master']['bill_pointsPrice'] > 0) {

                //检查账户积分
                $result_array = $this->eai->memberAccount( $bill_array['pcustID'], 3, $this->dbca, 0 );
                if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $surplus_money)
                    throw new Exception('账户良票不足', 406);

                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => 3,
                    'payTypeName' => '积分',
                    'type' => 5,
                    'pay_amount' => $bill_array['master']['bill_pointsPrice'],
                    'deduct_amount' => $bill_array['master']['bill_pointsPrice']
                );

                $temp_array['pay_id'][] = 3;
                $temp_array['pay_name'][] = '积分';

                $bill_array['points'] = array(
                    'payTypeID' => 3,
                    'payTypeName' => '积分',
                    'type' => 5,
                    'pay_amount' => $bill_array['master']['bill_pointsPrice'],
                    'deduct_amount' => $bill_array['master']['bill_pointsPrice']
                );

            }

            //保存订单支付信息
            if ($surplus_money >= 0 && $paid == 0) {
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => $bill_array['master']['payTypeID'],
                    'payTypeName' => $bill_array['master']['payTypeName'],
                    'type' => $bill_array['master']['pay_type'],
                    'pay_amount' => $surplus_money,
                    'deduct_amount' => 0
                );
                $temp_array['pay_id'][] = $bill_array['master']['payTypeID'];
                $temp_array['pay_name'][] = $bill_array['master']['payTypeName'];
            }

            //剩余订单金额等于0时，不开发票
            if ($surplus_money == 0 && isset($bill_array['master']['invoice']) && $bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice'] = 0;
                $bill_array['master']['invoiceID'] = null;
                $bill_array['master']['invoice_type'] = null;
                $bill_array['master']['invoice_title_type'] = null;
                $bill_array['master']['invoice_title'] = null;
                $bill_array['master']['invoice_content_id'] = null;
                $bill_array['master']['invoice_content'] = null;
            }

            //保存订单主表信息
            $bill_array['master']['uuid'] = make_uuid();
            $bill_array['master']['timeStamp'] = $datetime;
            $bill_array['master']['creator'] = $operator;
            $bill_array['master']['createTime'] = $datetime;
            $bill_array['master']['bill_no'] = $bill_no;
            $bill_array['master']['pcustID'] = $bill_array['pcustID'];
            $bill_array['master']['custID'] = $custID;
            $bill_array['master']['bill_status'] = 0;
            $bill_array['master']['pay_name_str'] = implode(',', $temp_array['pay_name']);
            $bill_array['master']['pay_id_str'] = implode(',', $temp_array['pay_id']);
            $bill_array['master']['goods_name_str'] = implode(',', $temp_array['goods']);

            if ($surplus_money == 0) {
                $bill_array['master']['pay_status'] = 1;
            } else if ($paid > 0) {
                $bill_array['master']['pay_status'] = 2;
            } else {
                $bill_array['master']['pay_status'] = 0;
            }
            $bill_array['master']['remark'] = $commHandler->convertVar($bill_array['master']['remark']);
            if (!isset($bill_array['master']['invoice'])) {
                $bill_array['master']['invoice'] = 0;
            } else if ($bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice_amount'] = $surplus_money;
            }
            $bill_array['master']['storeID'] = $commHandler->getStoreID();

            //保存订单轨迹信息
            $bill_array['trace'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                'creator' => $operator,
                'createTime' => $datetime,
                'bill_no' => $bill_no,
                'bill_status' => 0,
                'content' => '您已提交订单，请等待系统确认'
            );

            //保存会员购买记录
            $bill_array['cust_buy_log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                'creator' => $operator,
                'createTime' => $datetime,
                'pcustID' => $bill_array['pcustID'],
                'deliverID' => $bill_array['master']['deliverid'],
                'send_region_id' => $bill_array['master']['send_region_id'],
                'send_time_id' => $bill_array['master']['deliver_send_time_id'],
                'payTypeID' => $bill_array['master']['payTypeID'],
                'pay_type' => $bill_array['master']['pay_type'],
                'invoiceID' => isset($bill_array['master']['invoiceID']) ? $bill_array['master']['invoiceID'] : 0,
                'payment_method_id' => 0,
                'extend_1' => null,
                'extend_2' => null,
                'extend_3' => null,
                'extend_4' => null,
                'extend_5' => null,
                'extend_6' => null,
            );

            //=======================================
            // 订单日志
            //=======================================
            $bill_log_array['other'][] = '订单状态：建立';
            $bill_type_array = array(
                '1' => '前台订单',
                '2' => '手机app订单',
                '3' => 'wap订单' ,
                '4' => '后台订单' ,
                '5' => '淘宝订单' ,
                '6' => '京东订单' ,
                '7' => '1号店订单' ,
                '8' => '凡客订单' ,
                '9' => '补货单' ,
                '10' => '换货单',
                '11' => '闪购订单'
            );
            $bill_log_array['other'][] = '订单类型：' . $bill_type_array[$bill_array['master']['billType']];
            $bill_log_array['other'][] = '商品数量：' . $bill_array['master']['bill_totalAmount'];
            $bill_log_array['other'][] = '商品金额：' . $bill_array['master']['bill_totalPaid'] . '（不含运费）';
            $bill_log_array['other'][] = '　　运费：' . $bill_array['master']['deliver_fee'];
            $bill_log_array['other'][] = '应收金额：' . $bill_array['master']['bill_totalPaid'] + $bill_array['master']['deliver_fee'];
            $bill_log_array['other'][] = '赠送积分：' . $bill_array['master']['bill_totalPoints'];
            $bill_log_array['other'][] = '扣除积分：' . $bill_array['master']['bill_pointsPrice'];
            $bill_log_array['other'][] = '支付信息：';
            foreach($bill_array['pay'] as &$pay) {
                $bill_log_array['other'][] = '　　支付名称：' . $pay['payTypeName'];
                $bill_log_array['other'][] = '　　支付金额：' . $pay['pay_amount'];
            }
            if ($bill_array['master']['invoice'] == 1) {
                $bill_log_array['other'][] = '发票信息：';
                $bill_log_array['other'][] = '　　发票类型：商业零售发票';
                if ($bill_array['master']['invoice_title_type'] == 1)
                    $bill_log_array['other'][] = '　　发票抬头：（个人）' . $bill_array['master']['invoice_title'];
                else
                    $bill_log_array['other'][] = '　　发票抬头：（单位）' . $bill_array['master']['invoice_title'];
                $bill_log_array['other'][] = '　　发票内容：' . $bill_array['master']['invoice_content'];
                $bill_log_array['other'][] = '　　发票金额：' . $surplus_money;
            }
            $bill_log_array['operator'] = $operator;
            //=======================================
            // 订单日志
            //=======================================
            $bill_array['log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                'creator' => $operator,
                'createTime' => $datetime,
                'logCategoryID' => 1,
                'logItem' => $bill_no,
                'extend_1' => implode('<br>', $bill_log_array['other']),
                'extend_2' => implode('<br>', $bill_log_array['goods']),
                'extend_5' => 0
            );


            $bill_array['bill_no'] = $bill_no;

            //加密数据
            $bill_array['master']['deliver_name'] = encryptD($bill_array['master']['deliver_name']);
            $bill_array['master']['deliver_address'] = encryptD($bill_array['master']['deliver_address']);
            $bill_array['master']['deliver_mobile'] = encryptD($bill_array['master']['deliver_mobile']);
            $bill_array['master']['deliver_phone'] = encryptD($bill_array['master']['deliver_phone']);

            return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'bill_no' => $bill_no ) );

        } catch(Exception $e) {

            if ($e->getCode() > 0) {

                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );

            } else {

                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );

            }

        }

    }
	
    /**
     * 第三方订单保存
     * @param array $bill_array 订单数组
     * @param null|string $operator 操作人
     * @return array
     * @throws Exception
     */
    public function save3rdBill( &$bill_array, $shopID , $operator = null ) {
    	
    	$commHandler 	 = new commHandler( $this->dbca );					//实例化公共类
    	$customerHandler = new customerHandler( $this->dbca );				//实例化会员类
    	$goodsHandler 	 = new goodsHandler( $this->dbca );					//实例化商品类
    	$systemHandler	 = new systemHandler( $this->dbca );				//实例化系统类

		$bill_totalMoney = $bill_array['totalMoney'];						//商品总金额
		$bill_totalPaid	 = $bill_array['totalPaid'];						//商品实售总金额
		$deliver_fee	 = $bill_array['post_fee']	;						//订单运费
		$bill_totalPoints= 0;												//商品总赠送积分
		$bill_pointsPrice= 0;												//商品总积分价格
		$bill_totalAmount= 0;												//商品总数量
		$total_weight	 = 0;												//商品总重量
		
		$surplus_money 	 = $bill_totalPaid + $deliver_fee;					//应收金额（商品实际金额 + 运费）
		
		$bill_subtract_money = 0;											//订单立减
		$bill_coupon_money	 = 0;											//优惠券金额
		$bill_card_money	 = 0;											//礼品卡金额
		
		$payIdStr		= '';												//支付方式id字符串
		$payNameStr 	= '';												//支付方式名称字符串
		$goods_name_str = '';												//商品名称字符串
		$datetime 		= date(G_DEFAULT_DATETIME_FORMAT);					//下单时间
		$pay_status		= '';
		$save_array 	= array() ;
		
        try {
            //查询会员信息
            $arg_array = array(
                'pcustID' => $bill_array['pcustID'],
                'useFlg' => 1
            );
            
            $customer_array = $customerHandler->getCustomerInfo($arg_array);
            if (!$customer_array) {
                throw new Exception('会员信息没有找到', 404);
            }

            //会员名
            $custID =& $customer_array[0]['custID'];
			
            //如果操作人值为空，默认为会员名
            if (is_null($operator)) {
                $operator = $custID;
            }

            //订单号
            $bill_no = $commHandler->generate_seqno('seqno_bill');
            $bill_goods_array 	 = $bill_array['goods'];
            $bill_array['goods'] = array();

            //保存订单商品信息（普通商品）
            if (isset($bill_goods_array['general'])) {
                foreach ($bill_goods_array['general'] as &$g_l) {
                    //统计商品信息
                    $bill_totalAmount += $g_l['goods_amount'];	 							 	//商品总数量
                    $goods_name_str   .= $g_l['goodsName'] . '::'; 								//商品名称字符串
                    
                    //保存商品
                    $bill_goods_no = $commHandler->generate_seqno('seqno_bill_goods');
					$bill_goods = new entity('bill_goods');
					$bill_goods->creator 	   = $operator;
					$bill_goods->bill_no 	   = $bill_no;
					$bill_goods->bill_goods_no = $bill_goods_no;
					$bill_goods->goods_goodsID = $g_l['goodsID'];
					$bill_goods->goods_postID  = $g_l['postID'];
					$bill_goods->product_code  = $g_l['product_code'];
					$bill_goods->goods_name    = $g_l['goodsName'];
					$bill_goods->goods_spec    = $g_l['spec'];
					$bill_goods->goods_amount  = $g_l['goods_amount'];
					$bill_goods->goods_marketPrice 	 = $g_l['marketPrice'];
					$bill_goods->goods_storePrice  	 = $g_l['salePrice'];
					$bill_goods->goods_purchasePrice = $g_l['price'];
					$bill_goods->goods_pointsPrice   = $g_l['addPoints'];
					$bill_goods->goods_points   	 = $g_l['salePoints'];
					$bill_goods->goods_weight   	 = $g_l['goodsWeight'];
					$bill_goods->goods_from   	 	 = 1;
					$bill_goods->goods_groupID   	 = 0;
					$bill_goods->goods_status   	 = 1;
					$bill_goods->goods_time   	 	 = $datetime;

					$save_array[] = $bill_goods;
                    
                }

            }
            
            //判断商品数量是否为0
            if ($bill_totalAmount == 0){
                throw new Exception('订单商品为空，请选择商品', 406);
            }
			
			//订单内部留言
			if($bill_array['vender_remark'] != ''){
				$bill_remark = new entity('bill_remark');
				$bill_remark->creator = $operator;
				$bill_remark->bill_no = $bill_no;
				$bill_remark->remark  = $bill_array['vender_remark'];
				$save_array[] = $bill_remark;
			}

            //订单商品日志
			$bill_log_array = array(
				'goods' 	=> array(),
				'other' 	=> array(),
				'operator'	=> $operator
			);

            foreach ($bill_array['goods'] as &$b_goods) {
                $bill_log_array['goods'][] = sprintf('<span class="red">新增普通商品</span>：%s', $b_goods['goods_name']);
                $bill_log_array['goods'][] = '　　规格：' . $b_goods['goods_spec'];
                $bill_log_array['goods'][] = '　　数量：' . $b_goods['goods_amount'];
                $bill_log_array['goods'][] = '　　单价：' . $b_goods['goods_purchasePrice'];
                $bill_log_array['goods'][] = '优惠金额：' . round($b_goods['goods_storePrice'] - $b_goods['goods_purchasePrice'], 2);
                $bill_log_array['goods'][] = '　总金额：' . round($b_goods['goods_amount'] * $b_goods['goods_purchasePrice'], 2);
            }

            //保存订单支付信息
            if ($surplus_money >= 0) {
            	$bill_pay = new entity('bill_pay');
            	$bill_pay->creator 	   = $operator;
            	$bill_pay->bill_no 	   = $bill_no;
            	$bill_pay->payTypeID   = $bill_array['master']['payTypeID'];
            	$bill_pay->payTypeName = $bill_array['master']['payTypeName'];
            	$bill_pay->type 	   = $bill_array['master']['pay_type'];
            	$bill_pay->pay_amount  = $surplus_money;
            	$bill_pay->pay_time    = $bill_array['pay_time'];
            	$bill_pay->pay_code    = $bill_array['pay_code'];
            	$bill_pay->deduct_amount 	   = $surplus_money;
            	$bill_pay->paid_confirm_time   = $datetime;
            	$bill_pay->paid_confirmer 	   = 'system';
            	$bill_pay->paid_confirm_status = 1;
            	$save_array[] = $bill_pay;
            	
            	$payIdStr 	.= $bill_array['master']['payTypeID'] . '::';
            	$payNameStr .= $bill_array['master']['payTypeName'] . '::';
            }

            //剩余订单金额等于0时，不开发票
            if ($surplus_money == 0 && isset($bill_array['master']['invoice']) && $bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice'] 			= 0;
                $bill_array['master']['invoiceID'] 			= null;
                $bill_array['master']['invoice_type'] 		= null;
                $bill_array['master']['invoice_title_type'] = null;
                $bill_array['master']['invoice_title'] 		= null;
                $bill_array['master']['invoice_content_id'] = null;
                $bill_array['master']['invoice_content'] 	= null;
            }

            //保存订单主表信息
            $remark = $commHandler->convertVar($bill_array['master']['remark']);
            
            $bill_master = new entity('bill_master');
            $bill_master->creator 			 = $operator;
            $bill_master->bill_no 			 = $bill_no;
            $bill_master->pcustID 			 = $bill_array['pcustID'];
            $bill_master->custID  			 = $custID;
            $bill_master->extCustID   		 = $custID;
            $bill_master->bill_status 		 = 0;
            $bill_master->pay_status  		 = 1;
            $bill_master->remark 	  		 = $remark;
            $bill_master->storeID 		  	 = $commHandler->getStoreID();
            $bill_master->deliver_name 	 	 = encryptD($bill_array['master']['deliver_name']);
            $bill_master->deliver_address 	 = encryptD($bill_array['master']['deliver_address']);
            $bill_master->deliver_mobile  	 = encryptD($bill_array['master']['deliver_mobile']);
            $bill_master->deliver_phone   	 = encryptD($bill_array['master']['deliver_phone']);
            $bill_master->bill_totalMoney 	 = $bill_totalMoney;
            $bill_master->bill_totalPaid  	 = $bill_totalPaid;
            $bill_master->bill_totalPoints	 = $bill_totalPoints;
            $bill_master->bill_pointsPrice	 = $bill_pointsPrice;
            $bill_master->bill_subtract_money= $bill_pointsPrice;
            $bill_master->bill_coupon_money  = $bill_coupon_money;
            $bill_master->bill_card_money  	 = $bill_card_money;
            $bill_master->deliverid  	 	 = $bill_array['master']['deliverid'];
            $bill_master->deliver_province   = $bill_array['master']['deliver_province'];
            $bill_master->deliver_city   	 = $bill_array['master']['deliver_city'];
            $bill_master->deliver_county   	 = $bill_array['master']['deliver_county'];
            $bill_master->deliver_postalCode = $bill_array['master']['deliver_postalCode'];
            $bill_master->sendTypeID 	 	 = $bill_array['master']['sendTypeID'];
            $bill_master->sendTypeName 	 	 = $bill_array['master']['sendTypeName'];
            $bill_master->send_region_id 	 = $bill_array['master']['send_region_id'];
            $bill_master->send_region_name 	 = $bill_array['master']['send_region_name'];
            $bill_master->deliver_fee 	 	 = $deliver_fee;
            $bill_master->deliver_feePaid 	 = $deliver_fee;
            $bill_master->deliver_status 	 = 0;
            $bill_master->pay_type 	 	 	 = $bill_array['master']['pay_type'];
            $bill_master->payTypeID 	 	 = $bill_array['master']['payTypeID'];
            $bill_master->payTypeName 	 	 = $bill_array['master']['payTypeName'];
            $bill_master->pay_status 	 	 = $bill_array['master']['pay_status'];
            $bill_master->payed_time 	 	 = $bill_array['pay_time'];
            $bill_master->pay_id_str 	 	 = $payIdStr;
            $bill_master->pay_name_str 	 	 = $payNameStr;
            $bill_master->goods_name_str 	 = $goods_name_str;
            //$bill_master->billPlatform 	 = $bill_array['master']['billPlatform'];
            //$bill_master->billChannel 	 = $bill_array['master']['billChannel'];
            $bill_master->enterErp 	 	 	 = 0;
            $bill_master->shopCode 	 	 	 = $shopID;
            $bill_master->invoice 	 	 	 = $bill_array['master']['invoice'];
            $bill_master->invoiceID 	 	 = '';
            $bill_master->invoice_type 	 	 = '';
            $bill_master->invoice_title_type = $bill_array['master']['invoice_title_type'];
            $bill_master->invoice_title 	 = $bill_array['master']['invoice_title'];
            $bill_master->invoice_content_id = '';
            $bill_master->invoice_content 	 = $bill_array['master']['invoice_content'];
            $bill_master->invoice_amount 	 = $surplus_money;
            $bill_master->bill_totalAmount 	 = $bill_totalAmount;
            $save_array[] = $bill_master;

            //保存订单轨迹信息
            $bill_trace = new entity('bill_trace');
            $bill_trace->creator 	 = $operator;
            $bill_trace->bill_no 	 = $bill_no;
            $bill_trace->bill_status = 0;
            $bill_trace->content 	 = '您已提交订单并且已经付款成功 ，请等待系统确认 ';
            $save_array[] = $bill_trace;
            
            //保存会员购买记录
            $cust_buy_log = new entity('bill_cust_buy_log');
            $cust_buy_log->pcustID = $bill_array['pcustID'];
            if(!$this->dbca->fetch($cust_buy_log)){
            	$cust_buy_log->creator = $operator;
            }
            $cust_buy_log->pcustID 		  = $bill_array['pcustID'];
            $cust_buy_log->deliverID 	  = $bill_array['master']['deliverid'];
            $cust_buy_log->send_region_id = $bill_array['master']['send_region_id'];
            $cust_buy_log->send_time_id   = $bill_array['master']['deliver_send_time_id'];
            $cust_buy_log->payTypeID 	  = $bill_array['master']['payTypeID'];
            $cust_buy_log->pay_type 	  = $bill_array['master']['pay_type'];
            $cust_buy_log->invoiceID 	  = isset($bill_array['master']['invoiceID']) ? $bill_array['master']['invoiceID'] : 0;
            $cust_buy_log->payment_method_id = 0;
            
            $save_array[] = $cust_buy_log;
            
            // 订单日志
            $bill_log_array['other'][] = '订单状态：建立';
            $bill_log_array['other'][] = '订单类型：第三方平台订单';
            $bill_log_array['other'][] = '商品数量：' . $bill_totalAmount;
            $bill_log_array['other'][] = '商品金额：' . $bill_totalPaid . '（不含运费）';
            $bill_log_array['other'][] = '　　运费：' . $deliver_fee;
            $bill_log_array['other'][] = '应收金额：' . $bill_totalPaid + $deliver_fee;
            $bill_log_array['other'][] = '赠送积分：' . 0;
            $bill_log_array['other'][] = '扣除积分：' . 0;
            $bill_log_array['other'][] = '收货地址：';
            $bill_log_array['other'][] = '　　收货省份：' . $bill_array['master']['deliver_province'];
            $bill_log_array['other'][] = '　　收货市区：' . $bill_array['master']['deliver_city'];
            $bill_log_array['other'][] = '　　收货地区：' . $bill_array['master']['deliver_county'];
            $bill_log_array['other'][] = '　　收货地址：' . $bill_array['master']['deliver_address'];
            $bill_log_array['other'][] = '　　手机号码：' . $bill_array['master']['deliver_mobile'];
            $bill_log_array['other'][] = '　　电话号码：' . $bill_array['master']['deliver_phone'];
            $bill_log_array['other'][] = '配送方式：' . $bill_array['master']['sendTypeName'];
            $bill_log_array['other'][] = '配送区域：' . $bill_array['master']['send_region_name'];
            $bill_log_array['other'][] = '支付信息：';
            $bill_log_array['other'][] = '　　支付名称：' . $bill_array['master']['payTypeName'];
            $bill_log_array['other'][] = '　　支付金额：' . $surplus_money;
         
            if ($bill_array['master']['invoice'] == 1) {
                $bill_log_array['other'][] = '发票信息：';
                $bill_log_array['other'][] = '　　发票类型：商业零售发票';
                if ($bill_array['master']['invoice_title_type'] == 1){
                    $bill_log_array['other'][] = '　　发票抬头：（个人）' . $bill_array['master']['invoice_title'];
                }else{
                    $bill_log_array['other'][] = '　　发票抬头：（单位）' . $bill_array['master']['invoice_title'];
                }
                $bill_log_array['other'][] = '　　发票内容：' . $bill_array['master']['invoice_content'];
                $bill_log_array['other'][] = '　　发票金额：' . $surplus_money;
            }
            $bill_log_array['operator'] = $operator;
            
            //保存订单日志
            $bill_log = new entity('log_detail');
            $bill_log->creator 		 = $operator;
            $bill_log->logCategoryID = 1;
            $bill_log->logItem 		 = $bill_no;
            $bill_log->extend_1 	 = implode('<br>', $bill_log_array['other']);
            $bill_log->extend_2 	 = implode('<br>', $bill_log_array['goods']);
            $bill_log->extend_5  	 = 0 ;
            $save_array[] = $bill_log;

        } catch(Exception $e) {
            return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
        }

        //将数据保存到数据库
        $this->dbca->beginTransaction();
        try{
        	foreach($save_array as $s_l){
        		$this->dbca->save($s_l);
        	}
        	$this->dbca->commit();
        }catch(Exception $e) {
        	$this->dbca->rollBack();
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误');
        }
        
        return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'bill_no' => $bill_no ) );
    }


    /**
     * 查询团购订单
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'pcustID' => int 会员号
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
            'extend' => string 扩展sql
     * )
     * @return null|array
     */
    public function searchTuanBill( &$arg_array ) {

    		
    	//实例化商品类
    	$goodsHandler = new goodsHandler( $this->dbca );
    	
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
	
        //团购订单号
        if (isset($arg_array['bill_tuanNo']) && !empty($arg_array['bill_tuanNo'])) {
        	$sql .= ' AND bt.bill_tuanNo = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_tuanNo'];
        }
        	
        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND bt.bill_pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }
        
        //支付状态
        if (isset($arg_array['pay_status']) && is_numeric($arg_array['pay_status'])) {
            $sql .= ' AND bt.pay_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pay_status'];
        }
        
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
        
        $tuan_bill_array = array();
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_tuan bt ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY bt.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY bt.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }
			
            //查询团购订单
           	$search_sql = "SELECT bt.bill_tuanNo,bt.bill_time,bt.bill_paid,bt.deliver_reciever,bt.deliver_mannername,bt.deliver_status,
								bt.bill_status,bt.pay_status,pn.goodsMainPic,pn.goodsName,pn.goods_spec,bt.bill_money,
								bt.goods_amount,bt.goods_id,bt.goods_postID
							FROM bill_tuan bt JOIN goods_sale pn ON bt.goods_id=pn.goodsID ". $sql;
            $tuan_bill_list = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            
            if ($tuan_bill_list) {
            	foreach ($tuan_bill_list as $bill) {
            		$tuan_bill_array[] = array(
            			'bill_tuanNo' => $bill->bill_tuanNo,
            			'bill_time' => $bill->bill_time,
            			'bill_paid' => $bill->bill_paid,
            			'deliver_reciever' => $bill->deliver_reciever,
            			'deliver_mannername' => $bill->deliver_mannername,
            			'bill_status' => $bill->bill_status,
            			'pay_status' => $bill->pay_status,
            			'goodsMainPic' => $bill->goodsMainPic,
            			'goodsName' => $bill->goodsName,
            			'goods_spec' => $bill->goods_spec,
            			'bill_money' => $bill->bill_money,
            			'goods_tuanprice' => $bill->goods_tuanprice,
            			'goods_amount' => $bill->goods_amount,
            			'goods_id' => $bill->goods_id,
            			'goods_postID' => $bill->goods_postID,
            			'link' => $goodsHandler->setLink($bill->goods_postID),
            			'img_link' => $goodsHandler->setImgLink($bill->goodsMainPic),
            			'bill_link' => '/shop/member_order_detai-'.$bill->bill_tuanNo.'.html'
            		);
            	}
            }
			
            return $tuan_bill_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }
    

    /**
     * 查询订单主表信息
     * @param array $arg_array   查询参数数组
     * @return null|array
     */
    public function searchBillInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //会员名
        if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['custID'];
        }

        //下单开始日期
        if (isset($arg_array['startDate']) && !empty($arg_array['endDate'])) {
        	$sql .= ' AND createTime > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'].' 00:00:00';
        }
        
        //下单结束日期
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
        	$sql .= ' AND createTime < ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'].' 23:59:59';
        }
        
        //收货人
        if (isset($arg_array['deliver_name']) && !empty($arg_array['deliver_name'])) {
        	$sql .= ' AND deliver_name = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['deliver_name'];
        }
        
        //支付状态
        if (isset($_REQUEST['pay_status']) && in_array($_REQUEST['pay_status'],array('0', 1, 2))) {
        	$sql .= ' AND pay_type = ?';
            $params_type .= 'd';
            $params_array[] = $arg_array['pay_status'];
        }
        
        //订单状态
        if (isset($arg_array['bill_status']) && in_array($arg_array['bill_status'],array('0',1,2,3,4,5))) {
        	$sql .= ' AND bill_status = ?';
            $params_type .= 'd';
            $params_array[] = $arg_array['bill_status'];
        }

        //订单类型
        if (isset($arg_array['billType']) && is_numeric($arg_array['billType'])) {
            $sql .= ' AND billType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['billType'];
        }
        
        //支付方式
        if (isset($arg_array['pay_type']) && in_array($arg_array['pay_type'],array(1,2,3))) {
        	$sql .= ' AND pay_type = ?';
            $params_type .= 'd';
            $params_array[] = $arg_array['pay_type'];
        }

        //配送状态
        if (isset($arg_array['deliver_status']) && in_array($arg_array['deliver_status'],array('0',1,2,3))) {
        	$sql .= ' AND deliver_status = ?';
            $params_type .= 'd';
            $params_array[] = $arg_array['deliver_status'];
        }

        //退货状态
        if (isset($arg_array['withdraw_status']) && is_numeric($arg_array['withdraw_status']) ) {
            if ($arg_array['withdraw_status'] == 1) {
                $sql .= ' AND bill_withdrawAmount < bill_totalAmount AND bill_withdrawAmount > 0 ';
            } else if ($arg_array['withdraw_status'] == 2) {
                $sql .= 'AND bill_withdrawAmount = bill_totalAmount AND bill_withdrawAmount > 0 ';
            } else {
                $sql .= ' AND bill_withdrawAmount = 0 ';
            }
        }

        //拒收状态
        if (isset($arg_array['rejection_status']) && is_numeric($arg_array['rejection_status'])  ) {
            if ($arg_array['rejection_status'] == 1) {
                $sql .= ' AND bill_rejectionAmount < bill_totalAmount AND bill_rejectionAmount > 0 ';
            } else if ($arg_array['rejection_status'] == 2) {
                $sql .= 'AND bill_rejectionAmount = bill_totalAmount AND bill_rejectionAmount > 0 ';
            } else {
                $sql .= ' AND bill_rejectionAmount = 0 ';
            }
        }
        
        //手机号码
        if (isset($arg_array['deliver_mobile']) && is_numeric($arg_array['deliver_mobile'])) {
        	$sql .= ' AND deliver_mobile = ?';
            $params_type .= 'd';
            $params_array[] = $arg_array['deliver_mobile'];
        }

        /**
         * 商品名称
         */
        if (isset($arg_array['goods_name_str']) && !empty($arg_array['goods_name_str'])) {
            $sql .= ' AND goods_name_str LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['goods_name_str'] . '%';
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }
        
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_master' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_master' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }
            
            foreach ($temp_item_array as $bill) {

                //支付状态
                switch ($bill->pay_status) {
                    case '0':
                        $bill->pay_status_name = '未付款';
                        break;
                    case 1:
                        $bill->pay_status_name ='全付';
                        break;
                    case 2:
                        $bill->pay_status_name = '部分付';
                        break;
                }

                //订单状态
                switch ($bill->bill_status) {
                    case '0':
                        if ($bill->pay_type == 1 || $bill->pay_status == 1) {
                            $bill->bill_status_name = '待审核';
                        } else {
                            $bill->bill_status_name = '待付款';
                        }
                        break;
                    case 1:
                        $bill->bill_status_name = '已确认';
                        break;
                    case 2:
                        $bill->bill_status_name = '已发货';
                        break;
                    case 3:
                        $bill->bill_status_name = '已配送';
                        break;
                    case 4:
                        $bill->bill_status_name = '已完成';
                        break;
                    case 5:
                        $bill->bill_status_name = '已取消';
                        break;
                }

                //配送状态
                switch ($bill->deliver_status) {
                    case '0':
                        $bill->deliver_status_name = '等待发货';
                        break;
                    case 1:
                        $bill->deliver_status_name = '部分已发货';
                        break;
                    case 2:
                        $bill->deliver_status_name = '全部已发货';
                        break;
                    case 3:
                        $bill->deliver_status_name = '已收货确认';
                        break;
                }

                //退货状态
                if( $bill->bill_withdrawAmount == $bill->bill_totalAmount ){
                    $bill->bill_withdraw_name = '全部退货';
                }elseif ( $bill->bill_withdrawAmount > 0 && $bill->bill_withdrawAmount < $bill->bill_totalAmount ){
                    $bill->bill_withdraw_name = '部分退货';
                }else{
                    $bill->bill_withdraw_name = '未退货';
                }

                //拒收状态
                if( $bill->bill_rejectionAmount == $bill->bill_totalAmount ){
                    $bill->bill_rejection_name = '全部拒收';
                }elseif ( $bill->bill_rejectionAmount > 0 && $bill->bill_rejectionAmount < $bill->bill_totalAmount ){
                    $bill->bill_rejection_name = '部分拒收';
                }else{
                    $bill->bill_rejection_name = '未拒收';
                }

                switch($bill->billType) {
                    case 1:
                        $billTypeName = 'B2C商城订单';
                        break;
                    case 2:
                        $billTypeName = 'wap商城订单';
                        break;
                    case 3:
                        $billTypeName = '微信商城订单';
                        break;
                    case 4:
                        $billTypeName = '1号店订单';
                        break;
                    case 5:
                        $billTypeName = 'QQ网购订单';
                        break;
                    case 6:
                        $billTypeName = '凡客订单';
                        break;
                    case 7:
                        $billTypeName = '苏宁易购订单';
                        break;
                    case 8:
                        $billTypeName = '实体店订单';
                        break;
                    case 9:
                        $billTypeName = '补货单';
                        break;
                    case 10:
                        $billTypeName = '换货单';
                        break;
                   	case 11:
                        $billTypeName = '当当网订单';
                        break;

                }

                $item_array[] = array(
                    //订单信息
                    'bill_no' => $bill->bill_no,
                    'uuid' => $bill->uuid,
                    'timeStamp' => $bill->timeStamp,
                    'creator' => $bill->creator,
                    'createTime' => $bill->createTime,
                    'pcustID' => $bill->pcustID,
                    'custID' => $bill->custID,
                    'remark' => $bill->remark,
                    'bill_status' => $bill->bill_status,
                    'billType' => $bill->billType,
                    'billTypeName' => $billTypeName,
                    'bill_status_name' => $bill->bill_status_name,
                    'bill_cancel' => $bill->bill_cancel,
                    'bill_cancelTime' => $bill->bill_cancelTime,
                    'bill_totalMoney' => $bill->bill_totalMoney,
                    'bill_totalPaid' => $bill->bill_totalPaid,
                    'bill_totalPoints' => $bill->bill_totalPoints,
                    'bill_pointsPrice' => $bill->bill_pointsPrice,
                    'bill_totalAmount' => $bill->bill_totalAmount,
                    'bill_withdrawAmount' => $bill->bill_withdrawAmount,
                    'bill_rejectionAmount' => $bill->bill_rejectionAmount,
                    'bill_withdraw_name' => $bill->bill_withdraw_name,
                    'bill_rejection_name' => $bill->bill_rejection_name,
                    'bill_subtract_money' => $bill->bill_subtract_money,
                    'bill_coupon_money' => $bill->bill_coupon_money,
                    'bill_card_money' => $bill->bill_card_money,
                    'is_ext' => $bill->is_ext,
                    'extCustID' => $bill->extCustID,

                    //收货人信息
                    'deliverid' => $bill->deliverid, //收货地址ID
                    'deliver_name' => decryptD($bill->deliver_name), //收货人姓名
                    'deliver_province' => $bill->deliver_province, //收货地址省
                    'deliver_city' => $bill->deliver_city, //收货地址市
                    'deliver_county' => $bill->deliver_county, //收货地址区
                    'deliver_address' => decryptD($bill->deliver_address), //收货地址
                    'deliver_all_address' => $bill->deliver_province . $bill->deliver_city . $bill->deliver_county . decryptD($bill->deliver_address), //综合地址
                    'deliver_postalCode' => $bill->deliver_postalCode, //收货邮编
                    'deliver_mobile' => decryptD($bill->deliver_mobile), //收货人手机
                    'deliver_phone' => decryptD($bill->deliver_phone), //收货人电话

                    //配送
                    'sendTypeID' => $bill->sendTypeID, //配送方式ID
                    'sendTypeName' => $bill->sendTypeName, //配送方式名称
                    'send_region_name' => $bill->send_region_name, //配送区域名称
                    'send_region_id' => $bill->send_region_id, //配送区域ID
                    'deliver_fee' => $bill->deliver_fee, //应收运费
                    'deliver_feePaid' => $bill->deliver_feePaid, //实收运费
                    'deliver_status' => $bill->deliver_status, //配送状态
                    'deliver_status_name' => $bill->deliver_status_name, //配送状态
                    'deliver_time' => $bill->deliver_time, //配送状态变化时间
                    'deliver_send_time_id' => $bill->deliver_send_time_id, //送货时间ID
                    'deliver_send_time_name' => $bill->deliver_send_time_name, //送货时间名称

                    //付款
                    'pay_status' => $bill->pay_status, //付款状态
                    'pay_status_name' => $bill->pay_status_name, //付款方式名称
                    'payed_time' => $bill->payed_time, //付款时间
                    'pay_type' => $bill->pay_type, //支付方式类型
                    'payTypeID' => $bill->payTypeID, //支付方式ID
                    'payTypeName' => $bill->payTypeName, //支付方式名称

                    //发票信息
                    'invoice' => $bill->invoice,
                    'invoiceID' => $bill->invoiceID,
                    'invoice_type' => $bill->invoice_type,
                    'invoice_title_type' => $bill->invoice_title_type,
                    'invoice_title' => $bill->invoice_title,
                    'invoice_content_id' => $bill->invoice_content_id,
                    'invoice_content' => $bill->invoice_content,

                    'storeID' => $bill->storeID,
                    'package_no' => $bill->package_no,
                    'is_exception' => $bill->is_exception,
                    'bill_totalAmount' => $bill->bill_totalAmount,
                    'bill_withdrawAmount' => $bill->bill_withdrawAmount,
                    'bill_rejectionAmount' => $bill->bill_rejectionAmount,
                    'external_bill_no' => $bill->external_bill_no,
                    'extend_1' => $bill->extend_1,
                    'extend_2' => $bill->extend_2,
                    'extend_3' => $bill->extend_3,
                    'extend_4' => $bill->extend_4,
                    'extend_5' => $bill->extend_5,
                    'extend_6' => $bill->extend_6,
                    'extend_7' => $bill->extend_7,
                    'extend_8' => $bill->extend_8,
                    'extend_9' => $bill->extend_9,
                    'extend_10' => $bill->extend_10,
                    'extend_11' => $bill->extend_11,
                    'extend_12' => $bill->extend_12

                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询异常订单列表信息
     * $arg_array = array (
    					sortname' 	=> string 排序字段
   	 					array 		$arg_array                          查询参数数组
     					'sortorder' => string 排序方式
            			'page' 		=> int 分页页码
            			'rp' 		=> int 分页页数
     * )
     * @return null|array
     */
    public function searchBillWarning( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND pm.bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单类型
        if (isset($arg_array['billType']) && is_numeric($arg_array['billType'])) {
            $sql .= ' AND pm.billType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['billType'];
        }
        
        //订单渠道
        if (isset($arg_array['channel']) && is_numeric($arg_array['channel'])) {
            $sql .= ' AND bw.channel = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['channel'];
        }
        
        //收货人
        if (isset($arg_array['deliver_name']) && !empty($arg_array['deliver_name'])) {
        	$sql .= ' AND pm.deliver_name = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['deliver_name']);
        }

        //手机号码
        if (isset($_REQUEST['deliver_mobile']) && is_numeric($_REQUEST['deliver_mobile'])) {
        	$sql .= ' AND pm.deliver_mobile = ?';
            $params_type .= 's';
            $params_array[] = encryptD($arg_array['deliver_mobile']);
        }
		
        //物流状态
        if (isset($arg_array['freight_state']) && is_numeric($arg_array['freight_state'])) {
            $sql .= ' AND bw.freight_state = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['freight_state'];
        }
        
        //物流公司名称
        if (isset($_REQUEST['company_name']) && $_REQUEST['company_name'] !='') {
        	$sql .= ' AND bw.freight_company_name = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['company_name'];
        }
        
        //运单号
        if (isset($_REQUEST['freight_bill_no']) && $_REQUEST['freight_bill_no'] != '') {
        	$sql .= ' AND bw.freight_bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['freight_bill_no'];
        }
        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }
        
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {
                //统计数量
                $search_sql  = 'SELECT COUNT(*) count FROM bill_master pm INNER JOIN `bill_logistics_warning` bw ON pm.`bill_no`= bw.bill_no ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count  = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT pm.bill_no , pm.deliver_name , pm.deliver_mobile , pm.deliver_address , pm.billType,
							bw.`context`, bw.`freight_bill_no` , bw.`freight_company_name` , bw.`freight_state` FROM bill_master pm
							INNER JOIN `bill_logistics_warning` bw ON pm.`bill_no` = bw.`bill_no` ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
          
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }
    
    
    /**
     * 查询订单详情
     * @param array $arg_array 参数数组
     * @param object $G_GLOBAL 全局对象（如：$G_SHOP）
     * @return array|null
     */
    public function getBillDetail( $arg_array, $G_GLOBAL ) {

        if (!isset($arg_array['bill_no'], $arg_array['pcustID'])) {
            return null;
        }

        //查询redis里的订单信息
        $bill_index = $arg_array['bill_no'] . $arg_array['pcustID'];
        $bill_array = $G_GLOBAL->sessionCache_get('bill_' . $bill_index, true);
        if ($bill_array) {
            return $bill_array;
        }

        //查询订单主表信息
        $bill_master_array = $this->searchBillInfo( $arg_array );
        if (!$bill_master_array)
            return null;

        //查询订单支付信息
        $bill_pay_array = $this->searchBillPay( $arg_array );

        //查询订单商品信息
        $bill_goods_array = $this->searchBillGoods( $arg_array );

        //查询订单轨迹
        $bill_trace_array = $this->searchBillTrace( $arg_array );

        //生成订单数组
        $bill_array = array(

            'bill_no' => $arg_array['bill_no'],

            'bill_status' => 1,

            'change_time' => time(),

            'message' => 'ok',

            'goods' => $bill_goods_array,

            'pay' => $bill_pay_array,

            'master' => $bill_master_array[0],

            'pcustID' => $arg_array['pcustID'],

            'use_coupon' => array (
                'amount' => 0,
            ),

            'trace' => $bill_trace_array,

            'cust_buy_log' => array()

        );
        $G_GLOBAL->sessionCache_set('bill_' . $bill_index, $bill_array, 0, true);

        return $bill_array;

    }


    /**
     * 查询订单主表信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'bill_no' => int 订单号
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillGoods( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_goods ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT bg.*,gs.goodsMainPic,gs.twoPostID FROM bill_goods bg INNER JOIN goods_sale_edit gs ON gs.postID = bg.goods_postID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'bill_no' => $item->bill_no,
                        'bill_goods_no' => $item->bill_goods_no,
                        'goodsID' => $item->goods_goodsID,
                        'postID' => $item->goods_postID,
                        'goodsName' => $item->goods_name,
                        'spec' => $item->goods_spec,
                        'goods_amount' => $item->goods_amount,
                        'salePrice' => $item->goods_storePrice,
                        'price' => $item->goods_purchasePrice,
                        'addPoints' => $item->goods_pointsPrice,
                        'salePoints' => $item->goods_points,
                        'goods_from' => $item->goods_from,
                        'goods_groupID' => $item->goods_groupID,
                        'goods_status' => $item->goods_status,
                        'goods_time' => $item->goods_time,
                        'delivercount' => $item->goods_delivercount,
                        'remark' => $item->goods_remark,
                        'comment' => $item->comment_flg,
                        'link' => set_goods_link($item->goods_postID),
                        'wap_link' => set_wap_goods_link($item->goods_postID),
                        'imgLink' => set_goods_img_link($item->goodsMainPic),
                        'goods_withdrawAmount' => $item->goods_withdrawAmount,
                        'goods_rejectionAmount' => $item->goods_rejectionAmount,
                        'product_code' => $item->product_code,
                        'goodsMainPic' => $item->goodsMainPic,
                        'twoPostID' => $item->twoPostID
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }


    /**
     * 查询订单发放优惠券信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillCoupon( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //发放状态
        if (isset($arg_array['issue']) && in_array($arg_array['issue'], array(0, 1))) {
            $sql .= ' AND issue = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['issue'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_coupon ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_coupon ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'bill_no' => $item->bill_no,
                    'couponID' => $item->couponID,
                    'couponName' => $item->couponName,
                    'couponNum' => $item->couponNum,
                    'bill_status' => $item->bill_status,
                    'issue' => $item->issue
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }


    /**
     * 查询订单轨迹信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillTrace( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单状态
        if (isset($arg_array['bill_status']) && is_numeric($arg_array['bill_status'])) {
            $sql .= ' AND bill_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['bill_status'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_trace ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_trace ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            //实例化商品类
            $goodsHandler = new goodsHandler();

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'bill_no' => $item->bill_no,
                        'creator' => $item->creator,
                        'createTime' => $item->createTime,
                        'bill_status' => $item->bill_status,
                        'package_no' => $item->package_no,
                        'freight_company_name' => $item->freight_company_name,
                        'freight_websit' => $item->freight_websit,
                        'freight_bill_no' => $item->freight_bill_no,
                        'content' => $item->content
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询订单支付信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillPay( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //支付方式ID
        if (isset($arg_array['payTypeID']) && is_numeric($arg_array['payTypeID'])) {
            $sql .= ' AND payTypeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['payTypeID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_pay ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_pay ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

			
            //实例化商品类
            $goodsHandler = new goodsHandler();

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'bill_no' => $item->bill_no,
                        'payTypeID' => $item->payTypeID,
                        'payTypeName' => $item->payTypeName,
                        'type' => $item->type,
                        'pay_amount' => $item->pay_amount,
                        'deduct_amount' => $item->deduct_amount,
                        'pay_code' => $item->pay_code,
                        'pay_time' => $item->pay_time
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }
    
    /**
     * 查询订单内部留言
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
            'bill_no' => int 订单号
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillRemark( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_remark ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM bill_remark ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'bill_no' => $item->bill_no,
                        'creator' => $item->creator,
                        'createTime' => $item->createTime,
                        'remark' => $item->remark
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }


    /**
     * 添加订单内部留言
   	 * @param unknown_type $arg_array
     * @return unknown
     */
    public function saveBillInnerWord( &$arg_array ) {
		
    	//校验获取参数
        if (!isset($arg_array['remark'],$arg_array['bill_no']) || empty($arg_array['bill_no'])) {
        	return array( 'code' => 400, 'message' => '参数错误' );
        }
        
        if (empty($arg_array['remark'])) {
        	return array( 'code' => 400, 'message' => '请输入留言' );
        }
        
        $creator = $_REQUEST['creator'];
        $remark = $_REQUEST['remark'];
        $bill_no = $_REQUEST['bill_no'];
        
        try {

	        //查询订单号是否存在
	        $bill_master = new entity('bill_master');
	        $bill_master->bill_no = $bill_no;
	        if (!$this->dbca->fetch($bill_master))
                throw new Exception('订单信息不存在', 404);

	        $bill_remark = new entity('bill_remark');
	        $bill_remark->creator = $creator;
	        $bill_remark->bill_no = $bill_no;
	        $bill_remark->remark = $remark;
	        $this->dbca->save($bill_remark);
			
	        return array( 'code' => 200, 'message' => '添加成功', 'data' => array( 'createTime' => $bill_remark->createTime, 'remark' => $remark ) );
	        
        } catch (Exception $e) {
        	if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

    /**
     * 审核订单
     * @param $arg_array 参数数组
     * $arg_array = array (
     *       'bill_no' => int 订单号
     *       'operator' => string 操作人
     * )
     * @return array
     * @throws Exception
     */
    public function auditBill( $arg_array ) {

        //检查参数
        if (!isset($arg_array['bill_no'], $arg_array['operator']) || empty($arg_array['bill_no']))
            return array( 'code' => 400, 'message' => '参数错误' );

        try {

            $this->dbca->beginTransaction();

            //查询订单
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $arg_array['bill_no'];
            if (!$this->dbca->fetch($bill_master))
                throw new Exception('订单信息不存在', 404);

            if (in_array($bill_master->bill_status, array(1, 2, 3, 4)))
                throw new Exception('订单已审核，不能重复审核', 406);

            if ($bill_master->bill_status == 5)
                throw new Exception('订单已取消，审核失败', 406);

            if (($bill_master->pay_type == 2 || $bill_master->pay_type == 3) && ($bill_master->pay_status == 0 || $bill_master->pay_status == 2))
                throw new Exception('订单未付款，审核失败', 406);

            $bill_master->bill_status = 1;
            $this->dbca->save($bill_master);

            //实例化日志类
            $logHandler = new logHandler( $this->dbca );

            //保存日志
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_master->bill_no,
                'extend_1' => '订单审核',
                'extend_5' => 0,
                'operator' => $arg_array['operator']
            );
            $result_array = $logHandler->saveLogInfo( $log_array );
            if ($result_array['code'] != 200)
                throw new Exception('链接超时，请重试', 406);

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '订单审核成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }

    /**
     * 人工审核订单在线支付
     * @param array $arg_array 支付方式参数
     * @return array
     * @throws Exception
     */
    public function auditBillPay( $arg_array ) {
        //检查参数
        if (!isset($arg_array['bill_no'], $arg_array['operator'], $arg_array['payTypeID']) || empty($arg_array['bill_no']) || !is_numeric($arg_array['payTypeID']))
            return array( 'code' => 400, 'message' => '参数错误' );

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        //实例化日志类
        $logHandler = new logHandler( $this->dbca );

        try {
        	$bill_master = new entity('bill_master');
	        $bill_master->bill_no = $arg_array['bill_no'];
	        
			 //循环查询
            for($i = 0 ; $i < 3 ; $i++){
            	//查询订单
	            if ($this->dbca->fetch($bill_master))
	            	break ;
	            	
	            sleep(1) ;
            }
            
            if (!$bill_master)
	            throw new Exception('订单信息不存在', 404);
			
            if (in_array($bill_master->bill_status, array(1, 2, 3, 4)))
                throw new Exception('订单已审核', 406);

            if ($bill_master->bill_status == 5)
                throw new Exception('订单已取消，审核失败', 406);

            if ($bill_master->pay_type == 1 )
                throw new Exception('订单未付款，审核失败', 406);

            $bill_master->pay_status = 1;

            $this->dbca->beginTransaction();
            $this->dbca->save($bill_master);

            //检查订单支付方式并修改支付状态
            $bill_pay = new entity('bill_pay');
            $bill_pay->bill_no = $arg_array['bill_no'];
            $bill_pay->payTypeID = $arg_array['payTypeID'];
            if (!$this->dbca->fetch($bill_pay))
                throw new Exception('订单支付方式不存在', 404);

            if ($bill_pay->type == 1)
                throw new Exception('该支付方式为“货到付款”，不需要支付状态确认', 404);

            if ($bill_pay->deduct_amount == $bill_pay->pay_amount)
                throw new Exception('该支付方式已付款', 404);
            $bill_pay->deduct_amount = $bill_pay->pay_amount;
            $bill_pay->pay_code = isset($arg_array['pay_code']) ? $commHandler->convertVar($arg_array['pay_code']) : null;
            $bill_pay->pay_time = isset($arg_array['pay_time']) ? $commHandler->convertVar($arg_array['pay_time']) : null;
            $this->dbca->save($bill_pay);

            //更新订单轨迹
            $bill_trace = new entity('bill_trace');
            $bill_trace->creator = $arg_array['operator'];
            $bill_trace->bill_no = $arg_array['bill_no'];
            $bill_trace->bill_status = 0;
            $bill_trace->content = '您的订单付款成功';
            $this->dbca->save($bill_trace);

            //保存日志
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_master->bill_no,
                'extend_1' => '支付状态确认',
                'extend_5' => 0,
                'operator' => $arg_array['operator']
            );
            $result_array = $logHandler->saveLogInfo( $log_array );
            if ($result_array['code'] != 200)
                throw new Exception('链接超时，请重试', 406);

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '订单审核成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 订单取消
     * @param array $arg_array
     * $arg_array = array (
     *       'bill_no' => int 订单号
     *       'operator' => string 操作人
     *       'isException' => 1   [可选] 标记从异常订单处来的取消
     * )
     * @param object $eai
     * @return array
     */
    public function cancelBill( $arg_array, &$eai ) {

        //检查参数
        if (!isset($arg_array['bill_no'], $arg_array['operator']) || empty($arg_array['bill_no']))
            return array( 'code' => 400, 'message' => '参数错误' );

        try {

            //查询订单
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $arg_array['bill_no'];
            if (!$this->dbca->fetch($bill_master))
                throw new Exception('订单信息不存在', 404);

            if (isset($_REQUEST['source'])) {

                if ($bill_master->bill_status == 1)
                    throw new Exception('订单已确认，不能取消', 406);

                if ($bill_master->bill_status == 2)
                    throw new Exception('订单已发货，不能取消', 406);

            }

            if ($bill_master->bill_status == 3)
                throw new Exception('订单已配送，不能取消', 406);

            if ($bill_master->bill_status == 4)
                throw new Exception('订单已完成，不能取消', 406);

            if ($bill_master->bill_status == 5)
                throw new Exception('订单已取消，不能重复取消', 406);

            //实例化日志类
            $logHandler = new logHandler( $this->dbca );

            //订单日志参数
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_master->bill_no,
                'extend_1' => '订单取消',
                'extend_5' => $bill_master->bill_status,
                'operator' => $arg_array['operator']
            );

            //获取订单支付信息
            $pay_obj = array();
            $cash_array = array();//现金
            $points_array = array();//积分
            $pay_array = array(
                'bill_no' => $bill_master->bill_no
            );
            $result_pay = $this->searchBillPay($pay_array);
            foreach ($result_pay as $pay) {
                if ( $pay['type'] == 4) { //现金
                    $cash_array = array(
                        'pcustID' => $bill_master->pcustID,
                        'payTypeID' => $pay['payTypeID'],
                        'amount' => $pay['deduct_amount'],
                        'operator' => $arg_array['operator'],
                        'remark' => '订单：'. $bill_master->bill_no . '取消，冻结回滚',
                    );
                } else if ($pay['type'] == 5) { //积分
                    $points_array = array(
                        'pcustID' => $bill_master->pcustID,
                        'payTypeID' => $pay['payTypeID'],
                        'amount' => $pay['deduct_amount'],
                        'operator' => $arg_array['operator'],
                        'remark' => '订单：'. $bill_master->bill_no . '取消，冻结回滚',
                    );
                } else if ( ($pay['type'] == 2 || $pay['type'] == 3) && $pay['deduct_amount'] > 0 ) { //在线支付和汇款
                    $pay_obj[] = array(
                        'bill_no' => $bill_master->bill_no,
                        'return_no' => null,
                        'custID' => $bill_master->custID,
                        'payTypeID' => $pay['payTypeID'],
                        'payTypeName' => $pay['payTypeName'],
                        'refund_amount' => $pay['deduct_amount'],
                        'refund_source' => 3,
                        'operator' => $arg_array['operator']
                    );
                }
            }

            //查询订单使用的优惠券
            if ($bill_master->bill_coupon_money > 0) {

                //加载优惠券类
                quanli_require('module/base/couponHandler.class.php');

                //实例优惠券类
                $couponHandler = new couponHandler( $this->dbca );

                $bill_use_coupon_array = $this->searchBillUseCoupon( $bill_master->bill_no );

            }

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //取消订单
            $bill_master->bill_status = 5;
            $this->dbca->save($bill_master);

            //保存订单日志
            $result_array = $logHandler->saveLogInfo( $log_array );
            if ($result_array['code'] != 200) {
                throw new Exception('链接超时，请重试', 406);
            }

            //生成退款单
            if(!empty($pay_obj)){
                foreach ($pay_obj as $obj){
                    $this->saveBillRefund($obj,false);
                }
            }

            //回滚优惠券
            if (isset($bill_use_coupon_array) && !empty($bill_use_coupon_array)) {

                foreach($bill_use_coupon_array as &$coupon) {

                    if ($coupon['coupon_type'] == 1 || $coupon['coupon_type'] == 2)
                        $couponHandler->rollbackCoupon( $coupon['coupon_code'], $bill_master->bill_no);

                    $this->dbca->stmt_query('UPDATE bill_use_coupon SET isUse = 0 WHERE bill_no = ? AND coupon_code = ?', 'ss', $coupon['bill_no'], $coupon['coupon_code'] );

                }

            }

            if (!empty($cash_array)) {
                $eai->memberSubjectCancelLock($cash_array, $this->dbca);
            }

            if (!empty($points_array)) {
                $eai->memberSubjectCancelLock($points_array, $this->dbca);
            }

            $this->dbca->commit();

            $return_array = array(
                'bill_no' => $arg_array['bill_no'],
                'mobile' => decryptD($bill_master->deliver_mobile)
            );

            return array( 'code' => 200, 'message' => '订单取消成功', 'data' => $return_array );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }


    /**
     * 修改订单支付方式（只限在线支付）
     * @param array $arg_array 参数数组
     * @return array
     */
    public function changeBillPay( $arg_array ) {

        //检查参数
        if (!isset($arg_array['bill_no'], $arg_array['pcustID'], $arg_array['pay_id'], $arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (empty($arg_array['bill_no']) || empty($arg_array['operator']) || !is_numeric($arg_array['pcustID']) || !is_numeric($arg_array['pay_id'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            $this->dbca->beginTransaction();

            //检查支付方式
            $pay_obj = new entity('sys_paytype');
            $pay_obj->payTypeID = $arg_array['pay_id'];
            if (!$this->dbca->fetch($pay_obj)) {
                throw new Exception('支付方式信息没有找到', 404);
            }
            if ($pay_obj->type != 2) {
                throw new Exception('支付方式信息没有找到', 404);
            }

            //查询订单信息
            $bill_obj = new entity('bill_master');
            $bill_obj->bill_no = $arg_array['bill_no'];
            $bill_obj->pcustID = $arg_array['pcustID'];
            if (!$this->dbca->fetch($bill_obj)) {
                throw new Exception('订单信息没有找到', 404);
            }

            $bill_obj->pay_id_str = $pay_obj->payTypeID;
            $bill_obj->pay_name_str = $pay_obj->payTypeName;
            $bill_obj->payTypeID = $pay_obj->payTypeID;
            $bill_obj->payTypeName = $pay_obj->payTypeName;
            $this->dbca->save($bill_obj);

            //查询订单支付信息
            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->bill_no = $arg_array['bill_no'];
            $bill_pay_obj->type = 2;
            if (!$this->dbca->fetch($bill_pay_obj)) {
                throw new Exception('订单支付信息没有找到', 404);
            }
            $bill_pay_obj->payTypeID = $pay_obj->payTypeID;
            $bill_pay_obj->payTypeName = $pay_obj->payTypeName;
            $this->dbca->save($bill_pay_obj);

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => 'ok' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }


    /**
     * 查询异常订单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *        'sortname' => string 排序字段
     *        'sortorder' => string 排序方式
     *        'page' => int 分页页码
     *        'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillException (&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND be.bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单类型
        if (isset($arg_array['billType']) && is_numeric($arg_array['billType'])) {
            $sql .= ' AND bm.billType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['billType'];
        }

        //包裹号
        if (isset($arg_array['package_no']) && is_numeric($arg_array['package_no'])) {
            $sql .= ' AND package_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['package_no'];
        }

        //异常类型
        if (isset($arg_array['exception_type']) && is_numeric($arg_array['exception_type']) && $arg_array['exception_type'] > 0 ) {
            $sql .= ' AND exception_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['exception_type'];
        }

        //处理状态
        if (isset($arg_array['handle_status']) && is_numeric($arg_array['handle_status']) && $arg_array['handle_status'] >= 0 ) {
            $sql .= ' AND handle_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['handle_status'];
        }

        //生成日期--开始
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND be.createTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate']." 00:00:00";
        }

        //生成日期--结束
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND be.createTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate']." 23:59:59";
        }


        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_exception be INNER JOIN bill_master bm ON be.bill_no = bm.bill_no ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT bm.billType,be.*
                        FROM bill_exception be INNER JOIN bill_master bm ON be.bill_no = bm.bill_no ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            if ($temp_item_array) {

                //订单类型（来源）数组
                $bill_type_array = array(
                    '1' => 'B2C商城',
                    '2' => '天猫商城',
                    '3' => '京东商城',
                    '4' => '1号店',
                    '5' => 'QQ网购',
                    '6' => '凡客',
                    '7' => '苏宁易购',
                    '8' => '实体店',
                    '9' => '补货单',
                    '10' => '换货单'
                );

                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'uuid' => $item->uuid,
                        'handle_status' => $item->handle_status,
                        'bill_no' => $item->bill_no,
                        'billType' => $item->billType,
                        'billTypeName' => $bill_type_array[$item->billType],
                        'createTime' => $item->createTime,
                        'creator' => $item->creator,
                        'exception_type' => $item->exception_type,
                        'remark' => $item->remark,
                        'batch_no' => $item->batch_no,
                        'package_no' => $item->package_no,
                        'handler_user' => $item->handler_user,
                        'handler_time' => $item->handler_time,
                        'handler_remark' => $item->handler_remark
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 更新异常订单处理状态
     * @param array $arg_array
     * array(
     *        'bill_no' => int 订单号
     *       'operator' => string 操作人
     * )
     * @return array
     */
    public function updateBillExceptionStatus($arg_array){

        if(!isset($arg_array['id'],$arg_array['operator']) || empty($arg_array['id']) ){
            return array('code' => 400 , 'message' => '参数错误');
        }

        try{

            $bill_exception = new entity('bill_exception');
            $bill_exception->uuid = $arg_array['id'];
            if(!$this->dbca->fetch($bill_exception)){
                throw new Exception("未找到对应异常订单",404);
            }
            $bill_exception->handle_status = 1;
            $bill_exception->handler_user = $arg_array['operator'];
            $bill_exception->handler_time = date('Y-m-d H:i:s');
            $bill_exception->handler_remark = $arg_array['remark'];

            $this->dbca->save($bill_exception);

            return array('code' => 200 ,'message' => 'ok');
        }catch (Exception $e){
            error_log($e->getMessage());
            return array('code' => 500 ,'message' => '系统错误');
        }

    }



    /**
     * 查询退款单信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillRefund (&$arg_array){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND br.bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单类型
        if (isset($arg_array['billType']) && is_numeric($arg_array['billType'])) {
            $sql .= ' AND bm.billType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['billType'];
        }

        //退款单号
        if (isset($arg_array['refund_no']) && !empty($arg_array['refund_no'])) {
            $sql .= ' AND refund_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['refund_no'];
        }

        //会员名
        if (isset($arg_array['custID']) && !empty($arg_array['custID']) ) {
            $sql .= ' AND custID LIKE ?';
            $params_type .= 's';
            $params_array[] = "%".$arg_array['custID']."%";
        }

        //退货单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['return_no'];
        }

        //退款来源
        if (isset($arg_array['refund_source']) && is_numeric($arg_array['refund_source']) && $arg_array['refund_source'] > 0 ) {
            $sql .= ' AND refund_source = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['refund_source'];
        }


        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_refund br INNER JOIN bill_master bm ON br.bill_no = bm.bill_no ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT bm.billType,br.*
                        FROM bill_refund br INNER JOIN bill_master bm ON br.bill_no = bm.bill_no ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            if ($temp_item_array) {

                //订单类型（来源）数组
                $bill_type_array = array(
                    '1' => 'B2C商城',
                    '2' => '天猫商城',
                    '3' => '京东商城',
                    '4' => '1号店',
                    '5' => 'QQ网购',
                    '6' => '凡客',
                    '7' => '苏宁易购',
                    '8' => '实体店',
                    '9' => '补货单',
                    '10' => '换货单'
                );

                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,
                        'refund_no' => $item->refund_no,
                        'bill_no' => $item->bill_no,
                        'billType' => $item->billType,
                        'billTypeName' => $bill_type_array[$item->billType],
                        'return_no' => $item->return_no,
                        'custID' => $item->custID,
                        'payTypeName' => $item->payTypeName,
                        'refund_type_name' => $item->refund_type_name,
                        'refund_account' => $item->refund_account,
                        'payee' => $item->payee,
                        'refund_amount' => $item->refund_amount,
                        'refund_source' => $item->refund_source,
                        'refund_status' => $item->refund_status,
                        'remark' => $item->remark
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 保存退款单
     * @param array $arg_array
     * array(           保存参数
     *  'operator' => string  操作人  [必须]
     *  'refund_source' => int  退款来源  [必须]
     *  'refund_amount' => decimal  退款金额  [必须]
     *  'refund_no' => int  退款单号
     *  'bill_no' => int  订单号
     *  'return_no' => int  退货单号
     *  'custID' => string  会员名
     *  'pcustID' => int  客户号
     *  'payTypeID' => string  支付方式ID
     *  'payTypeName' => string  支付方式名称
     *  'refund_type_name' => string  退款方式
     *  'refund_account' => string  退款账户
     *  'payee' => string  收款人
     *  'remark' => string  备注
     * )
     * @param bool $transaction
     * @return array
     */
    public function saveBillRefund($arg_array , $transaction = true){

        //全站公共类
        $commHandler = new commHandler($this->dbca);

        if(!isset($arg_array['refund_source'] , $arg_array['refund_amount']) || !is_numeric($arg_array['refund_source']) || !$commHandler->isMoney($arg_array['refund_amount'])  ){
            return array('code' => 400 , 'message' => '参数错误');
        }


        try{

            //日志类
            $logHandler = new logHandler( $this->dbca );


            $bill_refund = new entity('bill_refund');
            if(!isset($arg_array['refund_no']) || !is_numeric($arg_array['refund_no']) ){       //走新建
                //生码
                $arg_array['refund_no'] = $commHandler->generate_seqno("seqno_refund");
                $bill_refund->refund_no = $arg_array['refund_no'];
                $extend_1 = "退款单建立";        //日志记录内容
            }else{              //走审核
                $bill_refund->refund_no = $arg_array['refund_no'];
                if(!$this->dbca->fetch($bill_refund)){
                    throw new Exception("未找到退款单信息" , 404);
                }

                if($bill_refund->refund_status == 2){
                    throw new Exception("该退款单已审核，不能重复审核" , 406);
                }
                if($bill_refund->refund_status == 3){
                    throw new Exception("该退款单已取消,审核失败" , 406);
                }
                $extend_1 = "退款单审核";
            }

            $bill_refund->creator = $arg_array['operator'];
            $bill_refund->bill_no = isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no']) ? $arg_array['bill_no'] : null;
            $bill_refund->return_no = isset($arg_array['return_no']) && !empty($arg_array['return_no']) ? $arg_array['return_no'] : null;
            $bill_refund->custID = isset($arg_array['custID']) ? $arg_array['custID'] : null;
            $bill_refund->pcustID = isset($arg_array['pcustID']) ? $arg_array['pcustID'] : null;
            $bill_refund->payTypeID = isset($arg_array['payTypeID']) ? $arg_array['payTypeID'] : null;
            $bill_refund->payTypeName = isset($arg_array['payTypeName']) ? $arg_array['payTypeName'] : null;
            $bill_refund->refund_type_name = isset($arg_array['refund_type_name']) ? $arg_array['refund_type_name'] : null;
            $bill_refund->refund_account = isset($arg_array['refund_account']) ? $arg_array['refund_account'] : null;
            $bill_refund->payee = isset($arg_array['payee']) ? $arg_array['payee'] : null;
            $bill_refund->refund_amount = $arg_array['refund_amount'];
            $bill_refund->return_time = isset($arg_array['refund_status']) && $arg_array['refund_status'] == 2 ? date('Y-m-d H:i:s') : null;
            $bill_refund->remark = isset($arg_array['remark']) ? $arg_array['remark'] : null;
            $bill_refund->refund_source = $arg_array['refund_source'];
            $bill_refund->refund_status = isset($arg_array['refund_status']) && is_numeric($arg_array['refund_status']) ? $arg_array['refund_status'] : 1;;

            //开启事务
            if($transaction){
                $this->dbca->beginTransaction();
            }


            //保存退款主表信息
            $this->dbca->save($bill_refund);

            //退款单日志参数
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_refund->refund_no,
                'extend_1' => $extend_1,
                'extend_5' => $bill_refund->refund_status,
                'operator' => $arg_array['operator']
            );
            $result_log = $logHandler->saveLogInfo($log_array);
            if($result_log['code'] != 200 ){
                throw new Exception("链接超时，请重试" , 406);
            }

            if($transaction){
                $this->dbca->commit();
            }

            return array('code' => 200 , 'message' => 'ok');

        }catch (Exception $e){

            if($transaction){
                $this->dbca->rollBack();
            }

            if( in_array($e->getCode(),array(404,406)) ){
                return array('code' => $e->getCode() , 'message' => $e->getMessage());
            }else{
                error_log($e->getMessage());
                return array('code' => 500 , 'message' => '系统错误，保存失败');
            }
        }

    }

    /**
     * 取消退款单
     */
    public function cancleBillRefund ($arg_array){

        if(!isset($arg_array['refund_no']) || !is_numeric($arg_array['refund_no']) ){
            return array( 'code' => 400 , 'message' => '参数错误' );
        }

        try{

            //日志类
            $logHandler = new logHandler($this->dbca);

            $bill_refund = new entity('bill_refund');
            $bill_refund->refund_no = $arg_array['refund_no'];
            if(!$this->dbca->fetch($bill_refund)){
                throw new Exception("未找到退款单信息" , 404);
            }

            if($bill_refund->refund_status == 2){
                throw new Exception("该退款单已审核，取消失败" , 406);
            }
            if($bill_refund->refund_status == 3){
                throw new Exception("该退款单已取消，不能重复取消" , 406);
            }

            $bill_refund->refund_status = 3;

            //开启事务
            $this->dbca->beginTransaction();

            //更新退款单主表
            $this->dbca->save($bill_refund);


            //退款单日志参数
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_refund->refund_no,
                'extend_1' => "退款单取消",
                'extend_5' => $bill_refund->refund_status,
                'operator' => $arg_array['operator']
            );
            $result_log = $logHandler->saveLogInfo($log_array);
            if($result_log['code'] != 200 ){
                throw new Exception("链接超时，请重试" , 406);
            }

            $this->dbca->commit();

            return array( 'code' => 200 , 'message' => '取消成功');

        }catch (Exception $e){

            $this->dbca->rollBack();

            if( in_array($e->getCode(),array(404,406))){
                return array('code' => $e->getCode() , 'message' => $e->getMessage());
            }else{
                error_log($e->getMessage());
                return array('code' => 500 , 'message' => '系统错误，取消失败');
            }
        }

    }

    /**
     * 查询退货/拒收主表信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *   'sortname' => string 排序字段
     *   'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillReturn (&$arg_array){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['bill_no']) && is_numeric($arg_array['bill_no'])) {
            $sql .= ' AND br.bill_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['bill_no'];
        }

        //订单类型
        if (isset($arg_array['billType']) && is_numeric($arg_array['billType'])) {
            $sql .= ' AND bm.billType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['billType'];
        }

        //退款单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['return_no'];
        }

        //会员名
        if (isset($arg_array['custID']) && !empty($arg_array['custID']) ) {
            $sql .= ' AND custID LIKE ?';
            $params_type .= 's';
            $params_array[] = "%".$arg_array['custID']."%";
        }

        //拒收/退货原因
        if (isset($arg_array['return_reason_id']) && is_numeric($arg_array['return_reason_id']) && $arg_array['return_reason_id'] > 0 ) {
            $sql .= ' AND return_reason_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_reason_id'];
        }

        //拒收还是退货
        if (isset($arg_array['return_type']) && is_numeric($arg_array['return_type']) && $arg_array['return_type'] > 0 ) {
            $sql .= ' AND return_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_type'];
        }

        //状态
        if (isset($arg_array['return_status']) && is_numeric($arg_array['return_status']) && $arg_array['return_status'] > 0 ) {
            $sql .= ' AND return_status = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['return_status'];
        }

        //创建开始时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
            $sql .= ' AND br.createTime > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate']." 00:00:00";
        }
        //创建结束时间
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
            $sql .= ' AND br.createTime < ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate']." 23:59:59";
        }

        //审核开始时间
        if (isset($arg_array['auditStartDate']) && !empty($arg_array['auditStartDate']) ){
            $sql .= ' AND confirm_time > ?';
            $params_type .= 's';
            $params_array[] = $arg_array['auditStartDate']." 00:00:00";
        }
        //审核结束时间
        if (isset($arg_array['auditEndDate']) && !empty($arg_array['auditEndDate']) ){
            $sql .= ' AND confirm_time < ?';
            $params_type .= 's';
            $params_array[] = $arg_array['auditEndDate']." 23:59:59";
        }


        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_return br INNER JOIN bill_master bm ON br.bill_no = bm.bill_no ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT br.*,bm.billType FROM bill_return br INNER JOIN bill_master bm ON br.bill_no = bm.bill_no ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            if ($temp_item_array) {

                //订单类型（来源）数组
                $bill_type_array = array(
                    '1' => 'B2C商城',
                    '2' => '天猫商城',
                    '3' => '京东商城',
                    '4' => '1号店',
                    '5' => 'QQ网购',
                    '6' => '凡客',
                    '7' => '苏宁易购',
                    '8' => '实体店',
                    '9' => '补货单',
                    '10' => '换货单'
                );

                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,
                        'return_no' => $item->return_no,
                        'bill_no' => $item->bill_no,
                        'billType' => $item->billType,
                        'billTypeName' => $bill_type_array[$item->billType],
                        'pcustID' => $item->pcustID,
                        'custID' => $item->custID,
                        'creator' => $item->creator,
                        'confirmor' => $item->confirmor,
                        'confirm_time' => $item->confirm_time,
                        'return_price' => $item->return_price,
                        'return_amount' => $item->return_amount,
                        'deliver_name' => $item->deliver_name,
                        'deliver_province' => $item->deliver_province,
                        'deliver_city' => $item->deliver_city,
                        'deliver_county' => $item->deliver_county,
                        'deliver_address' => $item->deliver_address,
                        'deliver_mobile' => $item->deliver_mobile,
                        'deliver_phone' => $item->deliver_phone,
                        'return_reason' => $item->return_reason,
                        'return_reason_id' => $item->return_reason_id,
                        'return_status' => $item->return_status,
                        'return_memo' => $item->return_memo,
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 订单退货/拒收
     * @param array $arg_array 参数数组
     * array(
     *      'bill_no' => 订单号
     *      'operator' => 操作人
     *      'datetime' => 操作时间
     * )
     * @return array
     */
    public function returnBill( $arg_array ) {

        if (!isset($arg_array['bill_no'], $arg_array['operator'], $arg_array['datetime'], $arg_array['return_type']) || !in_array($arg_array['return_type'], array(1, 2)) || empty($arg_array['bill_no']))
            return array( 'code' => 400, 'message' => '缺少参数，退货/拒收失败');

        //实例化公共类
        $commHandler = new commHandler($this->dbca);

        //字典类
        $itemHandler = new itemHandler($this->dbca);

        if (!isset($arg_array['reason']) || !is_numeric($arg_array['reason']))
            return array( 'code' => 400, 'message' => '请选择退货原因' );
        if (!isset($arg_array['custname']) || empty($arg_array['custname']))
            return array( 'code' => 400, 'message' => '请输入退货人' );
        if (!isset($arg_array['mobile']) || (!empty($arg_array['mobile']) && !$commHandler->isMobile($arg_array['mobile'])))
            return array( 'code' => 400, 'message' => '手机号码输入错误' );
        if (!isset($arg_array['phone']) || (!empty($arg_array['phone']) && !$commHandler->isPhone($arg_array['phone'])))
            return array( 'code' => 400, 'message' => '电话号码输入错误' );
        if (empty($arg_array['mobile']) && empty($arg_array['phone']))
            return array( 'code' => 400, 'message' => '手机号码和电话号码至少输入一项' );
        if (!isset($arg_array['provinceid'], $arg_array['cityid'], $arg_array['countyid']) || !is_numeric($arg_array['provinceid']) || !is_numeric($arg_array['cityid']) || !is_numeric($arg_array['countyid']))
            return array( 'code' => 400, 'message' => '请选择省市区' );
        if (!isset($arg_array['address']) || empty($arg_array['address']))
            return array( 'code' => 400, 'message' => '请输入地址' );
        if (!isset($arg_array['withdrawAmount']) || !is_array($arg_array['withdrawAmount']))
            return array( 'code' => 400, 'message' => '请选择退货商品' );

        $this->bill_no = $arg_array['bill_no'];

        $return_amount = 0; //退货商品数量
        $return_price = 0; //退货商品总金额
        $return_points = 0; //退货商品返还积分
        $deduct_points = 0; //退货商品扣除积分

        $bill_goods_array = array(); //订单商品数组
        $bill_return_goods_array = array(); //退货商品数组

        if ($arg_array['return_type'] == 1)
            $name = '退货';
        else
            $name = '拒收';

        try {

            //查询订单信息
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $this->bill_no;
            if (!$this->dbca->fetch($bill_master))
                throw new Exception(sprintf('订单号「%s」，订单信息没有找到，%s失败', $this->bill_no, $name), 404);
            if ($bill_master->bill_status == 5)
                throw new Exception(sprintf('订单号「%s」，订单已取消，无法%s', $this->bill_no, $name), 406);
            if (in_array($bill_master->bill_status, array(0, 1 )))
                throw new Exception(sprintf('订单号「%s」，订单未开始配送，无法%s', $this->bill_no, $name), 406);
            if ($arg_array['return_type'] == 1 && in_array($bill_master->bill_status, array(3)))
                throw new Exception(sprintf('订单号「%s」，订单未收货，无法%s，请拒收', $this->bill_no, $name), 406);
            if ($arg_array['return_type'] == 2 && $bill_master->bill_status == 4)
                throw new Exception(sprintf('订单号「%s」，订单已收货，无法%s，请退货', $this->bill_no, $name), 406);

            //查询退货/拒收原因
            $item_arg_array = array(
                'itemID' => $arg_array['reason'],
                'itemCategoryID' => $arg_array['return_type'] == 1 ? 8 : 9,
                'useFlg' => 1
            );
            $item_array = $itemHandler->getItemInfo($arg_array['reason']);
            if (!$item_array)
                throw new Exception($name . '原因信息没有找到', 404);

            //检查地区
            $province = new entity('sys_region');
            $province->id = $arg_array['provinceid'];
            $province->region_level = 1;
            if (!$this->dbca->fetch($province))
                throw new Exception('地区不存在', 404);

            $city = new entity('sys_region');
            $city->id = $arg_array['cityid'];
            $city->region_level = 2;
            if (!$this->dbca->fetch($city))
                throw new Exception('地区不存在', 404);

            $county = new entity('sys_region');
            $county->id = $arg_array['countyid'];
            $county->region_level = 3;
            if (!$this->dbca->fetch($county))
                throw new Exception('地区不存在', 404);


            foreach ($arg_array['withdrawAmount'] as $bill_goods_no => &$withdrawAmount) {

                if (!isset($bill_goods_no, $withdrawAmount) || !is_numeric($bill_goods_no) || !is_numeric($withdrawAmount))
                    throw new Exception($name . '商品信息错误，请核实', 404);
                if ($withdrawAmount == 0)
                    continue;

                //查询订单商品信息
                $bill_goods = new entity('bill_goods');
                $bill_goods->bill_no = $this->bill_no;
                $bill_goods->bill_goods_no = $bill_goods_no;
                if (!$this->dbca->fetch($bill_goods))
                    throw new Exception(sprintf('订单号「%s」，订单%s商品没有找到', $this->bill_no, $name), 404);
                if ($bill_goods->goods_amount - $bill_goods->goods_withdrawAmount - $bill_goods->goods_rejectionAmount < $withdrawAmount)
                    throw new Exception(sprintf('订单商品「%s」，%s数量大于可%s数量', $bill_goods->goods_name, $name, $name), 406);
                if ($arg_array['return_type'] == 1)
                    $bill_goods->goods_withdrawAmount += $withdrawAmount;
                else
                    $bill_goods->goods_rejectionAmount += $withdrawAmount;
                $bill_goods_array[] = $bill_goods;

                $return_amount += $withdrawAmount;
                $return_price += $bill_goods->goods_purchasePrice * $withdrawAmount;
                $return_points += $bill_goods->goods_pointsPrice * $withdrawAmount;
                $deduct_points += $bill_goods->goods_points * $withdrawAmount;

                //生成退货商品数组
                $bill_return_goods = new entity('bill_return_goods');
                $bill_return_goods->creator = $arg_array['operator'];
                $bill_return_goods->bill_goods_no = $bill_goods->bill_goods_no;
                $bill_return_goods->goods_postID = $bill_goods->goods_postID;
                $bill_return_goods->goods_goodsID = $bill_goods->goods_goodsID;
                $bill_return_goods->product_code = $bill_goods->product_code;
                $bill_return_goods->goods_name = $bill_goods->goods_name;
                $bill_return_goods->goods_spec = $bill_goods->goods_spec;
                $bill_return_goods->goods_amount = $withdrawAmount;
                $bill_return_goods->goods_flg = $bill_goods->goods_flg;
                $bill_return_goods_array[] = $bill_return_goods;

                //记录订单商品修改日志
                $bill_goods_alter_array[] = '<span class="red">' . $name . '商品</span>：' . $bill_goods->goods_name;
                $bill_goods_alter_array[] = '　　规格：' . $bill_goods->goods_spec;
                $bill_goods_alter_array[] = '　　数量：' . $withdrawAmount;
                $bill_goods_alter_array[] = '　　单价：' . $bill_goods->goods_purchasePrice;
                $bill_goods_alter_array[] = '优惠金额：' . round($bill_goods->goods_storePrice - $bill_goods->goods_purchasePrice, 2);
                $bill_goods_alter_array[] = '　总金额：' . round($withdrawAmount * $bill_goods->goods_purchasePrice, 2);

            }

            if($return_amount <= 0){
                throw new Exception(sprintf("请选择需要%s的商品及数量",$name) , 406);
            }

            //添加订单总订单退货或拒收数量
            if ($arg_array['return_type'] == 1) {
                $bill_master->bill_withdrawAmount += $return_amount;
            } else {
                $bill_master->bill_rejectionAmount += $return_amount;
            }

            //生成退货/拒收单信息
            $bill_return_master = new entity('bill_return');
            $bill_return_master->creator = $arg_array['operator'];
            $bill_return_master->bill_no = $this->bill_no;
            $bill_return_master->return_amount = $return_amount;
            $bill_return_master->custID = $bill_master->custID;
            $bill_return_master->pcustID = $bill_master->pcustID;
            $bill_return_master->return_price = $return_price;
            $bill_return_master->return_points = $return_points;
            if ($arg_array['return_type'] == 1)
                $bill_return_master->deduct_points = $deduct_points;
            else
                $bill_return_master->deduct_points = 0;
            $bill_return_master->deliver_name = $arg_array['custname'];
            $bill_return_master->deliver_province = $province->name;
            $bill_return_master->deliver_city = $city->name;
            $bill_return_master->deliver_county = $county->name;
            $bill_return_master->deliver_address = $arg_array['address'];
            $bill_return_master->deliver_mobile = $arg_array['mobile'];
            $bill_return_master->deliver_phone = $arg_array['phone'];
            $bill_return_master->return_reason_id = $item_array[0]->itemID;
            $bill_return_master->return_reason = $item_array[0]->itemName;
            $bill_return_master->return_memo = $arg_array['memo'];
            $bill_return_master->return_type = $arg_array['return_type'];
            $bill_return_master->return_status = 1;

            $bill_alter_array[] = $name . '数量：' . $return_amount;

            //实例化日志类
            $logHandler = new logHandler( $this->dbca );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => sprintf('系统错误，%s失败', $name) );
            }

        }

        try {

            $this->dbca->beginTransaction();

            $this->dbca->save($bill_master, 'bill');

            //保存订单商品信息
            foreach($bill_goods_array as &$bill_goods_obj) {
                $this->dbca->save($bill_goods_obj, 'bill');
            }


            //保存退货单主表信息
            $bill_return_master->return_no = $commHandler->generate_seqno('seqno_return');
            $bill_return_master->return_no = str_pad($bill_return_master->return_no,8,0,STR_PAD_LEFT);
            if ($arg_array['return_type'] == 1){
                $bill_return_master->return_no = "TH".$bill_return_master->return_no;
            }else{
                $bill_return_master->return_no = "JS".$bill_return_master->return_no;
            }

            $this->dbca->save($bill_return_master, 'bill');


            //保存退货商品
            foreach($bill_return_goods_array as &$bill_return_goods_obj) {
                $bill_return_goods_obj->return_no = $bill_return_master->return_no;
                $this->dbca->save($bill_return_goods_obj, 'bill');
            }

            $bill_alter_array[] = $name . '单号：' . $bill_return_master->return_no;

            $log_arg_array['logItem'] = $this->bill_no;
            $log_arg_array['logCategoryID'] = 1;
            $log_arg_array['operator'] = $arg_array['operator'];
            $log_arg_array['extend_1'] = implode('<br>', $bill_alter_array);
            $log_arg_array['extend_2'] = implode('<br>', $bill_goods_alter_array);
            $log_arg_array['extend_5'] = $bill_master->bill_status;

            //保存订单日志
            $logHandler->saveLogInfo( $log_arg_array );

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();
            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => sprintf('系统错误，%s失败', $name) );
            }

        }

        return array( 'code' => 200, 'message' => sprintf('订单%s成功', $name) );

    }


    /**
     * 查询退货/拒收商品信息
     * @param array $arg_array                          查询参数数组
         * $arg_array = array (
            'return_no' => int 退货单号
            'sortname' => string 排序字段
            'sortorder' => string 排序方式
            'page' => int 分页页码
            'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchBillReturnGoods( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单号
        if (isset($arg_array['return_no']) && !empty($arg_array['return_no'])) {
            $sql .= ' AND return_no = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['return_no'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }


        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM bill_return_goods ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM bill_return_goods ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);


            //实例化商品类
            $goodsHandler = new goodsHandler();

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'return_no' => $item->return_no,
                        'bill_goods_no' => $item->bill_goods_no,
                        'goodsID' => $item->goods_goodsID,
                        'postID' => $item->goods_postID,
                        'goodsName' => $item->goods_name,
                        'spec' => $item->goods_spec,
                        'goods_amount' => $item->goods_amount
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }



    /**
     * 退货/拒收单状态修改
     * @param array $arg_array 参数数组
     * $arg_array = array(
     *      'type' => int 2、审核 3、取消【必选】
     *      'return_no' => string 退货/拒收单号【必选】
     *      'operator' => string 操作人【可选】
     *      'datetime' => string 操作时间【可选】
     * )
     * @return array
     * @throws Exception
     */
    public function alterBillReturn( $arg_array  ) {

        try {

            //查询退货/换货单信息
            $return = new entity('bill_return');
            $return->return_no = $arg_array['return_no'];
            if (!$this->dbca->fetch($return))
                throw new Exception(sprintf('退货/换货单「%s」信息没有找到', $arg_array['return_no']), 404);

            if ($return->return_type == 1) {
                $name = '退货';
            } else {
                $name = '拒收';
            }

            if ($arg_array['type'] == 2) {
                //退货/换货审核检查
                if ($return->return_status == 2)
                    throw new Exception(sprintf('%s单「%s」已审核，不能重复审核', $name, $arg_array['return_no']), 406);
                if ($return->return_status == 3)
                    throw new Exception(sprintf('%s单「%s」已取消，审核失败', $name, $arg_array['return_no']), 406);
            } else if ($arg_array['type'] == 4) {
                //退货/换货取消检查
                if ($return->return_status == 2)
                    throw new Exception(sprintf('%s单「%s」已审核，取消失败', $name, $arg_array['return_no']), 406);
                if ($return->return_status == 3)
                    throw new Exception(sprintf('%s单「%s」已取消，不能重复取消', $name, $arg_array['return_no']), 406);
            }

            if ($arg_array['type'] == 2){
                $return->return_status = 2;
                $return->confirm_time = $arg_array['datetime'];
                $return->confirmor = $arg_array['operator'];
            }else {
                $return->return_status = $arg_array['type'];
            }

            //订单主表信息
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $return->bill_no;
            $this->dbca->fetch($bill_master);


            if ($arg_array['type'] == 3) {   //退货/审核单取消

                //取消订单退货/换货数量（数组）
                $bill_goods_array = array();

                $bill_return_goods_array = $this->dbca->stmt_query('SELECT * FROM bill_return_goods WHERE return_no=?', 's', $arg_array['return_no']);
                foreach ($bill_return_goods_array as &$goods) {

                    $bill_goods = new entity('bill_goods');
                    $bill_goods->bill_no = $return->bill_no;
                    $bill_goods->goods_postID = $goods->goods_postID;
                    if (!$this->dbca->fetch($bill_goods))
                        throw new Exception('订单商品没有找到', 404);
                    if ($return->return_type == 1)
                        $bill_goods->goods_withdrawAmount -= $goods->goods_amount;
                    else
                        $bill_goods->goods_rejectionAmount -= $goods->goods_amount;
                    $bill_goods_array[] = $bill_goods;

                    //记录订单商品修改日志
                    $bill_goods_alter_array[] = '<span class="red">取消' . $name . '商品</span>：' . $bill_goods->goods_name;
                    $bill_goods_alter_array[] = '　　数量：' . $goods->goods_amount;

                }

                $bill_alter_array[] = '取消' . $name . '单号：' . $return->return_no;

                //减少订单主表退货/拒收总数量
                if ($return->return_type == 1)
                    $bill_master->bill_withdrawAmount -= $return->return_amount;
                else
                    $bill_master->bill_rejectionAmount -= $return->return_amount;

            } else if ($arg_array['type'] == 2) {   //退货/拒收单审核

                //生成退款单数组
                $refund_array = array (
                    'refund_source' => $return->return_type,
                    'refund_amount' => $return->return_price,
                    'operator' => $arg_array['operator'],
                    'return_no' => $return->return_no,
                    'custID' => $return->custID,
                    'pcustID' => $return->pcustID,
                    'bill_no' => $return->bill_no,
                );

                //查询积分的支付方式
                $result_pay = $this->dbca->stmt_query("SELECT * FROM sys_paytype WHERE type = 5");

                //退货/拒收退回积分
                if ($return->return_type == 1) {
                    $points = $return->return_points - $return->deduct_points;
                } else {
                    $points = $return->return_points;
                }

                if ($points != 0) {
                    $account_array = array(
                        'payTypeID' => $result_pay[0]->payTypeID,
                        'payTypeName' => '积分',
                        'pcustID' => $return->pcustID ,
                        'operator' => $arg_array['operator'],
                        'useableAccount' => $points,
                        'changeType' => 1,
                        'billNo' => $return->bill_no,
                        'memo' => '订单' . $name
                    );
                }


                //日志
                $bill_alter_array[] = '审核' . $name . '单号：' . $return->return_no;

                //库存增加对应退货/拒收的商品数量
                $bill_return_goods_array = $this->dbca->stmt_query('SELECT goods_goodsID,SUM(goods_amount) AS goods_amount FROM bill_return_goods WHERE return_no=? GROUP BY goods_goodsID', 's', $arg_array['return_no']);
                $wms_goodsstore = new entity('wms_goodsstore');
                $wms_goodsstore->storeID = $bill_master->storeID;
                $wms_goodsstore->goodsID = $bill_return_goods_array[0]->goods_goodsID;
                $this->dbca->fetch($wms_goodsstore);
                $wms_goodsstore->enableSaleAmount = $wms_goodsstore->enableSaleAmount > 0 ? $wms_goodsstore->enableSaleAmount : 0;
                $wms_goodsstore->enableSaleAmount += $bill_return_goods_array[0]->goods_amount;

            }

            //实例化日志类
            $logHandler = new logHandler( $this->dbca );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //更新退货/拒收单
            $this->dbca->save($return);

            //更新订单商品退货数量
            if (isset($bill_goods_array) && !empty($bill_goods_array)) {
                foreach ($bill_goods_array as &$goods_obj) {
                    $this->dbca->save($goods_obj);
                }
            }


            if ($arg_array['type'] == 3) {

                $this->dbca->save($bill_master, 'bill');

                $log_arg_array['logItem'] = $return->bill_no;
                $log_arg_array['logCategoryID'] = 1;
                $log_arg_array['operator'] = $arg_array['operator'];
                $log_arg_array['extend_1'] = implode('<br>', $bill_alter_array);
                $log_arg_array['extend_2'] = implode('<br>', $bill_goods_alter_array);
                $log_arg_array['extend_5'] = -1;

                //保存日志
                $logHandler->saveLogInfo( $log_arg_array );

            } else if ($arg_array['type'] == 2) {

                //生成退款单
                $this->saveBillRefund($refund_array , false);


                //日志
                $log_arg_array['logItem'] = $return->bill_no;
                $log_arg_array['logCategoryID'] = 1;
                $log_arg_array['operator'] = $arg_array['operator'];
                $log_arg_array['extend_1'] = implode('<br>', $bill_alter_array);
                $log_arg_array['extend_5'] = -1;
                $logHandler->saveLogInfo($log_arg_array);

                //用户积分

                if ($points != 0) {
                    $customerHandler = new customerHandler($this->dbca);
                    $result = $customerHandler->customerAccount( $account_array );
                    if ($result['code'] != 200)
                        throw new Exception($result['message']);
                }

                //库存增加
                $this->dbca->save($wms_goodsstore);

            }

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误，操作失败' );
            }

        }

        if ($arg_array['type'] == 2)
            return array( 'code' => 200, 'message' => sprintf('%s单审核成功', $name) );
        elseif ($arg_array['type'] == 3)
            return array( 'code' => 200, 'message' => sprintf('%s单取消成功', $name) );

    }

    /**
     * 查询订单使用的优惠券
     * @param int $bill_no 订单号
     * @return null
     */
    public function searchBillUseCoupon( $bill_no ) {

        $search_sql = 'SELECT * FROM bill_use_coupon WHERE bill_no = ?';
        $coupon_array = &$this->dbca->stmt_query($search_sql, 's', $bill_no);
        if (!$coupon_array) {
            return null;
        }

        foreach($coupon_array as &$coupon) {
            $item_array[] = array(
                'bill_no' => $coupon->bill_no,
                'coupon_code' => $coupon->coupon_code,
                'coupon_name' => $coupon->coupon_name,
                'isUse' => $coupon->isUse,
                'coupon_type' => $coupon->coupon_type
            );
        }

        return $item_array;

    }


}